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


当前回答

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' 

其他回答

--for oracle
select tablespace_name, table_name from all_tables;

这个链接可以提供更多的信息 主题

SELECT sobjects.name
FROM sysobjects sobjects
WHERE sobjects.xtype = 'U' 
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 ''?'''

INFORMATION_SCHEMA的缺点。它还包括系统表,如dtproperties和MSpeer_…表,没有办法把它们和你自己的表区分开来。

我建议使用sys。对象(已弃用的sysobjects视图的新版本),它支持排除系统表:

select *
from sys.objects
where type = 'U'      -- User tables
and is_ms_shipped = 0 -- Exclude system tables