首页 > 开发 > 综合 > 正文

找SQL表的主键

2024-07-21 02:08:27
字体:
来源:转载
供稿:网友

1:利用sql自带的存储过程

exec sp_pkeys @table_name='表名'

2:利用系统表information_schema.key_column_usage

select table_name,column_name from information_schema.key_column_usage
where table_name='表名'

3: 以下这个查询表结构的语句可能大家都见过:

利用syscolumns,sysindexes,sysindexkeys三个表关联可以查出主键

select
 (case when a.colorder=1 then d.name else '' end) n'表名',
 a.colorder n'字段序号',
 a.name n'字段名',
 (case when columnproperty( a.id,a.name,'isidentity')=1 then '√'else '' end) n'标识',
 (case when (select count(*)
 from sysobjects
 where (name in
           (select name
          from sysindexes
          where (id = a.id) and (indid in
                    (select indid
                   from sysindexkeys
                   where (id = a.id) and (colid in
                             (select colid
                            from syscolumns
                            where (id = a.id) and (name = a.name))))))) and
        (xtype = 'pk'))>0 then '√' else '' end) n'主键',
 b.name n'类型',
 a.length n'占用字节数',
 columnproperty(a.id,a.name,'precision') as n'长度',
 isnull(columnproperty(a.id,a.name,'scale'),0) as n'小数位数',
 (case when a.isnullable=1 then '√'else '' end) n'允许空',
 isnull(e.text,'') n'默认值',
 isnull(g.[value],'') as n'字段说明'
--into ##tx

from  syscolumns  a left join systypes b
on  a.xtype=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 sysproperties g
on a.id=g.id and a.colid = g.smallid 
order by object_name(a.id),a.colorder


4:


select o.name as 表名,c.name as 字段名,k.colid as 字段序号,k.keyno as 索引顺序 from sysindexes i
join sysindexkeys k on i.id = k.id and i.indid = k.indid
join sysobjects o on i.id = o.id
join syscolumns c on i.id=c.id and k.colid = c.colid
where o.xtype = 'u'
and exists(select 1 from sysobjects where xtype = 'pk' and name = i.name)
order by o.name,k.colid


 
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表