MSSQL_查詢Table是否有Primary Key

  • 6944
  • 0

摘要:MSSQL_查詢Table是否有Primary Key

找出資料庫中沒有 primary key 的 table

select a.name as tablename, b.name as pkname from sysobjects a
 left join sysobjects b
on b.parent_obj = a.id and b.xtype='PK'
 and b.type='K' where a.xtype='U' and a.type='U'
order by a.name

其中 a 是查 table 用的
所以 a.xtype='U' 及 a.type='U' 是找出 table 的條件
而 b 是用來對照 a 用的查找 primary key 用的
所以對應條件為 b.parent_obj = a.id 用來找出屬於 a 的子物件,
所以再加上 b.xtype='PK' 及 b.type='K' 代表找出 b 是 primary key
如此一來便能查找出所有 table 對應的 primary key
由於是使用 left join 的方式
若是沒有 primary key 的 table
則會找出 null (沒有對應到)