SQL系统视图,系统表,系统存储过程的使用
获取数据库中用户表信息
1、获取特定库中所有用户表信息
select * from sys.tables
select * from sys.objects where type='U' --用户表
第二条语句中当type='S'时是系统表
2、获取表的字段信息
select * from sys.columns where object_id=object_id('表名')
select * from syscolumns where id=OBJECT_ID('表名' )
3、获取当前库中表的字段及类型信息
(1)select '字段名'=a.name,
'类型名'=b.name,
'字段长度'=a.max_length,
'参数顺序'=a.column_id
from sys.columns a left join sys.types b
on a.user_type_idsqlserver2012数据库还原=b.user_type_id
where object_id=object_id('表名')
syscolumns与lumns表用法类似。
获取索引或主键信息
1、获取对象及对应的索引的信息
select '对象名'=A.name,
'对象类型'=a.type,
'索引名'=B.name,
'索引类型'=case b.type when 1 then '聚集索引'
when 2 then '非聚集索引'
when 3 then 'xml索引'
else '空间索引' end,
'主键否'=case when b.is_primary_key=1 then '主键'
else '' end
FROM sys.objects A JOIN sys.indexes B ON A.object_id=B.object_id
WHERE A.type='U' AND B.name IS NOT NULL order by a.name
2、获取表的主键及对应的字段
(1)select '表名'=d.name ,'主键名'=a.name,'字段名'=c.name
from sys.indexes a join sys.index_columns b
on a.object_id=b.object_id and a.index_id=b.index_id
join sys.columns c on a.object_id=c.object_id and
c.column_id=b.column_id
join sys.objects d on d.object_id=c.object_id
where a.is_primary_key=1
(2)SELECT '表名'=OBJECT_NAME(b.parent_obj),
'主键名'=c.name,
'字段名'=a.name
FROM syscolumns a,sysobjects b,sysindexes c,sysindexkeys d
WHERE b.xtype = 'PK' AND b.parent_obj = a.id AND c.id = a.id
AND b.name = c.name AND d.id = a.id
AND d.indid = c.indid AND a.colid = d.colid
(3)select '所属架构'=s.name ,
'表名'=t.name,
'主键名'=k.name ,
'列名'=c.name,
'键列序数'=ic.key_ordinal
from sys.key_constraints as k
join sys.tables as t
on t.object_id = k.parent_object_id
join sys.schemas as s
on s.schema_id = t.schema_id
join sys.index_columns as ic
on ic.object_id = t.object_id
and ic.index_id = k.unique_index_id
join sys.columns as c
on c.object_id = t.object_id
and c.column_id = ic.column_id where k.type = 'pk';
(4)使用系统存储过程获取指定表的主键信息
EXEC sp_pkeys '表名' --表名只能是当前数据库下的单独表名不能带上架构名
3、查询哪些表创建了主键
select '表名'=a.name from
(select name,object_id from sys.objects where type='u') a
left join
sys.indexes b
on a.object_id=b.object_id and b.is_primary_key=1
where b.name is not null
注:查询哪些表没有创建主键,将where条件改成 is null 即可。
查视图信息
1、查看视图属性信息
exec sp_help '视图名'
2、查看创建视图脚本
exec sp_helptext '视图名'
3、查看当前数据库所有视图基本信息
select * from sys.views
select * from sys.objects where type='V'
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论