赞
踩
在SQL Server中查询数据库表和字段的方式可以有三种
#####方法一
-- 查询所有表 SELECT * FROM sys.tables; -- 查询所有列 SELECT * FROM sys.columns; -- 查询所有扩展属性,我们在设计数据库表和字段时写的中文备注等信息会保存在这里 SELECT * FROM sys.extended_properties; -- 查询字段类型 SELECT * FROM sys.types; -- 数据库表与字段联合查询 SELECT sys.tables.name AS 数据表名, sys.columns.name AS 字段名称, sys.types.name AS 字段类型, sys.columns.max_length AS 类型长度, sys.columns.is_nullable AS 是否允许为NULL, (SELECT value FROM sys.extended_properties WHERE sys.extended_properties.major_id = sys.columns.object_id AND sys.extended_properties.minor_id = sys.columns.column_id) AS 字段描述 FROM sys.columns, sys.tables, sys.types WHERE sys.columns.object_id = sys.tables.object_id AND sys.columns.system_type_id=sys.types.system_type_id;
#####方法二
-- 查询所有表 SELECT * FROM sysobjects d where d.xtype='U' and d.name<>'dtproperties'; -- 查询所有列 SELECT * FROM syscolumns; -- 查询字段类型 SELECT * FROM systypes; -- 数据库表与字段联合查询 SELECT 表名=CASE WHEN a.colorder=1 THEN d.name ELSE '' END, 表说明=CASE WHEN a.colorder=1 THEN isnull(f.value,'') ELSE '' END, 字段序号=a.colorder, 字段名=a.name, 标识=CASE WHEN COLUMNPROPERTY(a.id,a.name,'IsIdentity')=1 THEN '√' ELSE '' END, 主键=CASE WHEN EXISTS(SELECT 1 FROM sysobjects WHERE xtype='PK' AND name IN( SELECT name FROM sysindexes WHERE indid IN( SELECT indid FROM sysindexkeys WHERE id = a.id AND colid=a.colid ))) THEN '√' ELSE '' END, 类型=b.name, 占用字节数=a.length, 长度=COLUMNPROPERTY(a.id,a.name,'PRECISION'), 小数位数=ISNULL(COLUMNPROPERTY(a.id,a.name,'Scale'),0), 允许空=CASE WHEN a.isnullable=1 THEN '√' ELSE '' END, 默认值=ISNULL(e.text,''), 字段说明=ISNULL(g.[value],'') FROM syscolumns a LEFT JOIN systypes b ON a.xusertype=b.xusertype INNER JOIN sysobjects d ON a.id=d.id and d.xtype='U' AND d.name<>'dtproperties' 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 LEFT JOIN sys.extended_properties f ON d.id=f.major_id AND f.minor_id=0 ORDER BY a.id,a.colorder
注意:syscolumns与sys.columns、systypes与sys.types并不是同一张表
方法三
在SQL Server中存在表information_schema.tables
和information_schema.columns
我们可以通过这两张表来查询需要的字段。(注意:mysql中同样存在这两张表,但字段会有所不同,在mysql中有table_comment
和column_comment
字段可以查询到数据表描述和字段描述信息,而SQL Server中的这两张表中并没有这两个字段
)
-- 查询所有表
SELECT * FROM information_schema.tables;
-- 查询所有字段
SELECT * FROM information_schema.columns;
-- 数据库表与字段联合查询,该方法在SQL Server无法查询到表和字段备注
SELECT table_name AS 数据表名,
column_name AS 字段名,
ISNULL(column_default,'') AS 默认值,
is_nullable AS 是否允许为NULL,
data_type AS 数据类型,
ISNULL(ISNULL(ISNULL(character_maximum_length,numeric_precision),datetime_precision),1) AS 类型长度
FROM information_schema.columns
WHERE NOT table_name IN('sysdiagrams','dtproperties');
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。