sqlserver 查询数据表
1. 如何获取所有架构及其包含的数据表名称
SELECT s.name AS 架构名称, t.name AS 数据表名称 FROM sys.schemas s INNER JOIN sys.tables t ON s.schema_id = t.schema_id ORDER BY s.name, t.name;
在这个查询中:
sys.schemas
视图包含数据库中所有架构的信息。s.name
字段表示架构的名称。sys.tables
视图包含数据库中所有用户表的信息。t.name
字段表示表的名称。s.schema_id = t.schema_id
条件用于将架构与其包含的表关联起来。ORDER BY s.name, t.name
子句用于按架构名称和表名称对结果进行排序。
执行这个查询后,你将得到一个结果集,其中包含所有架构及其包含的数据表的名称。每个架构下的表将按表名称排序列出。
2. 查询数据表的数据字典包含架构
SELECT (CASE WHEN a.colorder = 1 THEN schema_name.name + '.' + d.name ELSE '' END) AS 表名, a.colorder AS 字段序号, a.name AS 字段名, (CASE WHEN COLUMNPROPERTY(a.id, a.name, 'IsIdentity') = 1 THEN '√' ELSE '' END) AS 标识, (CASE WHEN EXISTS ( SELECT 1 FROM sysobjects so INNER JOIN sysindexes si ON so.id = si.id INNER JOIN sysindexkeys sik ON si.id = sik.id AND si.indid = sik.indid WHERE so.id = a.id AND so.xtype = 'U' AND sik.colid = a.colid AND EXISTS ( SELECT 1 FROM sysobjects pk WHERE pk.parent_obj = si.id AND pk.xtype = 'PK' ) ) THEN '√' ELSE '' END) AS 主键, b.name AS 类型, a.length AS 占用字节数, COLUMNPROPERTY(a.id, a.name, 'PRECISION') AS 长度, ISNULL(COLUMNPROPERTY(a.id, a.name, 'Scale'), 0) AS 小数位数, (CASE WHEN a.isnullable = 1 THEN '√' ELSE '' END) AS 允许空, ISNULL(e.text, '') AS 默认值, ISNULL(g.[value], '') AS 字段说明, schema_name.name AS 架构名 FROM syscolumns a LEFT JOIN systypes b ON a.xtype = b.xusertype INNER JOIN sysobjects d ON a.id = d.id AND d.xtype = 'U' AND d.name <> 'dtproperties' INNER JOIN sys.schemas schema_name ON d.uid = schema_name.schema_id -- 加入架构信息 LEFT JOIN syscomments e ON a.cdefault = e.id LEFT JOIN sys.extended_properties g ON a.id = g.major_id AND a.colid = g.minor_id ORDER BY schema_name.name, -- 首先按架构排序 d.name, a.id, a.colorder;
来自雨中上人的文章