文章目录
本文参考:https://blog.csdn.net/josjiang1/article/details/80558068。
也可以直接点击这里文章链接: sql server查询表结构(字段名,数据类型,长度,描述,是否允许为空,是否为主键)。
初步理解
小步测试
- 先查询表的ID
sql
use [DBName];
--在数据库的用户表列表sys.objects中查询表的ID
select object_id from sys.objects where name='[tbName]';
- 查询表的信息
sql
--查询表的信息:字段名、类型、是否为空
select * from sys.columns where object_id = 645577338;
对于我来说足够了。
组合一下
将上面两句组合一下:
sql
use [DBName];
select * from sys.columns where object_id = (select object_id from sys.objects where name='[tbName]');
参考文章有更详细评述
sql
use [DBName];
select
col. name as ColumnName,
col.max_length as DataLength,
col.is_nullable as IsNullable,
t. name as DataType,
ep.value as Description,
(
select top 1 ind.is_primary_key from sys.index_columns ic
left join sys.indexes ind
on ic.object_id=ind.object_id
and ic.index_id=ind.index_id
and ind. name like 'PK_%'
where ic.object_id=obj.object_id
and ic.column_id=col.column_id
) as IsPrimaryKey
from sys.objects obj
inner join sys.columns col
on obj.object_id=col.object_id
left join sys.types t
on t.user_type_id=col.user_type_id
left join sys.extended_properties ep
on ep.major_id=obj.object_id
and ep.minor_id=col.column_id
and ep. name = 'MS_Description'
where obj. name ='[tbName]';
可以读出的更详细
继续理解
得到大部分信息
查询INFORMATION_SCHEMA.COLUMNS里的信息:
sql
use [DBName];
SELECT TOP 10 * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '[tbName]';
得到的结果如下:
这些字段的具体含义可以看这里官方文档。