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


当前回答

请用这个。你会得到表名和模式名:

SELECT SYSSCHEMA.NAME, SYSTABLE.NAME
FROM SYS.tables SYSTABLE
INNER JOIN SYS.SCHEMAS SYSSCHEMA
ON SYSTABLE.SCHEMA_ID = SYSSCHEMA.SCHEMA_ID

其他回答

在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 等。

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.
USE YourDBName
GO 
SELECT *
FROM sys.Tables
GO

OR

USE YourDBName
GO
SELECT * FROM INFORMATION_SCHEMA.TABLES 
GO

SQL Server 2000, 2005, 2008, 2012, 2014, 2016, 2017或2019:

SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE'

仅显示来自特定数据库的表

SELECT TABLE_NAME 
FROM [<DATABASE_NAME>].INFORMATION_SCHEMA.TABLES 
WHERE TABLE_TYPE = 'BASE TABLE'

Or,

SELECT TABLE_NAME 
FROM INFORMATION_SCHEMA.TABLES 
WHERE TABLE_TYPE = 'BASE TABLE' 
    AND TABLE_CATALOG='dbName' --(for MySql, use: TABLE_SCHEMA='dbName' )

PS: SQL Server 2000:

SELECT * FROM sysobjects WHERE xtype='U' 
exec sp_msforeachtable 'print ''?'''