在我们工作,学习,开发中,为了快速了解业务,编写业务,需要了解相关的表的信息,下面这个SQL就很有必要了。这个SQL能让我们使用快捷键就能查看指定表的信息(字段、备注、索引、约束信息等),能让我们迅速了解到相关表的信息。下面就是具体的设置方法。
CREATE procedure [dbo].[sp_helpex]
@objname nvarchar(256) = NULL -- object name we're after
as
begin
set nocount on
set @objname=replace ( @objname , '[' , '' )
set @objname=replace ( @objname , ']' , '' )
-- @objname must be either sysobjects or systypes: first look in sysobjects
declare @objid int
declare @sysobj_type char(2)
select @objid = object_id, @sysobj_type = type from sys.all_objects where object_id = object_id(@objname)
if @objid is null
begin
return
end
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 parent_obj=a.id 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
where
d.name=@objname
order by
a.id,a.colorder
-- DISPLAY COLUMN IF TABLE / VIEW
-- DISPLAY TABLE INDEXES & CONSTRAINTS
if @sysobj_type in ('S ','U ')
begin
print ' '
EXEC sys.sp_helpindex @objname
print ' '
EXEC sys.sp_helpconstraint @objname,'nomsg'
if (select count(*) from sys.objects obj, sysdepends deps
where obj.type ='V' and obj.object_id = deps.id and deps.depid = @objid and deps.deptype = 1) = 0
begin
raiserror(15647,-1,-1,@objname) -- No views with schemabinding reference table '%ls'.
end
else
begin
select distinct 'Table is referenced by views' = obj.name from sys.objects obj, sysdepends deps
where obj.type ='V' and obj.object_id = deps.id and deps.depid = @objid
and deps.deptype = 1 group by obj.name
end
end
else if @sysobj_type in ('V ')
begin
print ' '
raiserror(15469,-1,-1,@objname) -- No constraints defined
print ' '
raiserror(15470,-1,-1,@objname) -- No foreign keys reference table '%ls'.
EXEC sys.sp_helpindex @objname
end
end
GO
我们可以直接使用SQL语句进行查询也可以设置成快捷键进行查询。
示例:
exec sp_helpex '表名'
设置SQL Server快捷键查询的方法
打开SQL Server,点击工具,然后点击选项。
然后,添加快捷键就ok了。
以上就是SQL Server使用快捷键查看指定表的信息(字段、备注、索引、约束信息等)的方法啦。