在SQL Server上获得特定数据库中所有表的名称的最佳方法是什么?


当前回答

在SSMS中,要获得特定数据库(例如,“MyDatabase”)中的所有全限定表名:

SELECT [TABLE_CATALOG] + '.' + [TABLE_SCHEMA] + '.' + [TABLE_NAME]
FROM   MyDatabase.INFORMATION_SCHEMA.Tables
WHERE  [TABLE_TYPE] = 'BASE TABLE' and [TABLE_NAME] <> 'sysdiagrams'
ORDER BY [TABLE_SCHEMA], [TABLE_NAME]

结果:

MyDatabase.dbo.MyTable1 MyDatabase.dbo.MyTable2 MyDatabase.MySchema.MyTable3 MyDatabase.MySchema.MyTable4 等。

其他回答

使用SELECT * FROM INFORMATION_SCHEMA。COLUMNS还显示所有表和相关列。

SELECT * FROM information_schema.tables
where TABLE_TYPE = 'BASE TABLE'

SQL Server 2012

Any of the T-SQL code below will work in SQL Server 2019:

-- here, you need to prefix the database name in INFORMATION_SCHEMA.TABLES
SELECT TABLE_NAME FROM [MSSQL-TEST].INFORMATION_SCHEMA.TABLES;

-- The next 2 ways will require you to point
-- to the specific database you want to list the tables

USE [MSSQL-TEST];
-- (1) Using sys.tables
SELECT * FROM sys.tables;

-- (2) Using sysobjects
SELECT * FROM sysobjects
WHERE type='U';

Here’s a working example using [Skyvia] using sys.tables.

[Skyvia] should be the link to https://skyvia.com/connectors/sql-server


  [1]: https://i.stack.imgur.com/o3qo9.png

Your SQL GUI tool should also have a way to list down all the tables in a database like the one above.

So, whatever suits your need and taste, there’s a code or GUI tool for that.
exec sp_msforeachtable 'print ''?'''

select * from sysobjects where xtype='U'