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


当前回答

感谢Ray Vega,他的响应给出了数据库中的所有用户表…

Exec sp_msforeachtable 'print " ?“‘

Sp_helptext显示了底层查询,它总结为…

select * from dbo.sysobjects o 
join sys.all_objects syso on o.id =  syso.object_id  
where OBJECTPROPERTY(o.id, 'IsUserTable') = 1 
and o.category & 2 = 0 

其他回答

要删除复制添加的表和微软添加的任何其他表,请运行以下命令:

SELECT s.NAME SchemaName, t.NAME TableName
FROM [dbname].SYS.tables t
INNER JOIN [dbname].SYS.SCHEMAS s
ON t.SCHEMA_ID = s.SCHEMA_ID
WHERE t.is_ms_shipped=0 and type_desc = 'USER_TABLE'
ORDER BY s.NAME, t.NAME

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

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

select *
from sys.objects
where type = 'U'      -- User tables
and is_ms_shipped = 0 -- Exclude system tables
SELECT * FROM information_schema.tables
where TABLE_TYPE = 'BASE TABLE'

SQL Server 2012

SELECT sobjects.name
FROM sysobjects sobjects
WHERE sobjects.xtype = 'U'

下面是你可以搜索的其他对象类型的列表:

AF: Aggregate function (CLR) C: CHECK constraint D: Default or DEFAULT constraint F: FOREIGN KEY constraint L: Log FN: Scalar function FS: Assembly (CLR) scalar-function FT: Assembly (CLR) table-valued function IF: In-lined table-function IT: Internal table P: Stored procedure PC: Assembly (CLR) stored-procedure PK: PRIMARY KEY constraint (type is K) RF: Replication filter stored procedure S: System table SN: Synonym SQ: Service queue TA: Assembly (CLR) DML trigger TF: Table function TR: SQL DML Trigger TT: Table type U: User table UQ: UNIQUE constraint (type is K) V: View X: Extended stored procedure

感谢Ray Vega,他的响应给出了数据库中的所有用户表…

Exec sp_msforeachtable 'print " ?“‘

Sp_helptext显示了底层查询,它总结为…

select * from dbo.sysobjects o 
join sys.all_objects syso on o.id =  syso.object_id  
where OBJECTPROPERTY(o.id, 'IsUserTable') = 1 
and o.category & 2 = 0