系统视图,系统表,系统存储过程的使用
Posted claireyuancy
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了系统视图,系统表,系统存储过程的使用相关的知识,希望对你有一定的参考价值。
系统视图,系统表,系统存储过程的使用
获取数据库中用户表信息
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_id=b.user_type_id
where object_id=object_id(\'表名\')
syscolumns与sys.columns表使用方法类似。
获取索引或主键信息
-
获取对象及相应的索引的信息
select \'对象名\'=A.name,
\'对象类型\'=a.type,
\'索引名\'=B.name,
\'索引类型\'=case b.type when 1 then \'聚集索引\'
when2 then \'非聚集索引\'
when3 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
-
获取表的主键及相应的字段
(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 \'表名\' --表名仅仅能是当前数据库下的单独表名不能带上架构名
-
查询哪些表创建了主键
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 就可以。
查找视图信息
-
查看视图属性信息
exec sp_help \'视图名\'
-
查看创建视图脚本
exec sp_helptext \'视图名\'
-
查看当前数据库全部视图基本信息
select * from sys.views
select * from sys.objects where type=\'V\'
以上是关于系统视图,系统表,系统存储过程的使用的主要内容,如果未能解决你的问题,请参考以下文章