找SQL表的主鍵

2021-04-12 12:09:02 字數 1967 閱讀 1238

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='表名'

利用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.**allid 

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

sql 主鍵表與外來鍵表的區分

主鍵 表和外建表是相對來說的,簡單的說就是乙個表的 主鍵是另外一張表的外來鍵。例如class 班級表主要字段如下 classid primary key 主鍵 班級id classname 班級名稱 studen 學生表主要字段如下 stuid primary key 主鍵 學生id stuname...

SQL主鍵表與外來鍵表的區分

主鍵 表和外建表是相對來說的,簡單的說就是乙個表的 主鍵是另外一張表的 外來鍵。例如 class 班級表主要字段如下 classid primary key 主鍵 班級id classname 班級名稱 studen 學生表主要字段如下 stuid primary key 主鍵 學生id stuna...

SQL取資料表主鍵

1 select table name,column name from information schema.key column usage where table name dtproperties 2 exec sp pkeys table name 表名 3 select o.name a...