Sql Server 約束查詢

2021-09-02 08:43:58 字數 2105 閱讀 9960

主鍵約束

select

tab.name as [表名],

idx.name as [主鍵名稱],

col.name as [主鍵列名]

from

sys.indexes idx

join sys.index_columns idxcol

on (idx.object_id = idxcol.object_id

and idx.index_id = idxcol.index_id

and idx.is_primary_key = 1)

join sys.tables tab

on (idx.object_id = tab.object_id)

join sys.columns col

on (idx.object_id = col.object_id

and idxcol.column_id = col.column_id);

唯一約束

select

tab.name as [表名],

idx.name as [約束名稱],

col.name as [約束列名]

from

sys.indexes idx

join sys.index_columns idxcol

on (idx.object_id = idxcol.object_id

and idx.index_id = idxcol.index_id

and idx.is_unique_constraint = 1)

join sys.tables tab

on (idx.object_id = tab.object_id)

join sys.columns col

on (idx.object_id = col.object_id

and idxcol.column_id = col.column_id);

外來鍵約束

select

osub.name as [子表名稱],

fk.name as [外來鍵名稱],

subcol.name as [子表列名],

omain.name as [主表名稱],

maincol.name as [主表列名]

from

sys.foreign_keys fk

join sys.all_objects osub

on (fk.parent_object_id = osub.object_id)

join sys.all_objects omain

on (fk.referenced_object_id = omain.object_id)

join sys.foreign_key_columns fkcols

on (fk.object_id = fkcols.constraint_object_id)

join sys.columns subcol

on (osub.object_id = subcol.object_id

and fkcols.parent_column_id = subcol.column_id)

join sys.columns maincol

on (omain.object_id = maincol.object_id

and fkcols.referenced_column_id = maincol.column_id)

check約束

select

tab.name as [表名],

chk.name as [check約束名],

col.name as [列名],

chk.definition

from

sys.check_constraints chk

join sys.tables tab

on (chk.parent_object_id = tab.object_id)

join sys.columns col

on (chk.parent_object_id = col.object_id

and chk.parent_column_id = col.column_id)

sql server 約束 查詢

fk 外來鍵 主鍵約束 select tab.name as 表名 idx.name as 主鍵名稱 col.name as 主鍵列名 from sys.indexes idx join sys.index columns idxcol on idx.object id idxcol.object ...

sql server 約束 查詢

fk 外來鍵 主鍵約束 select tab.name as 表名 idx.name as 主鍵名稱 col.name as 主鍵列名 from sys.indexes idx join sys.index columns idxcol on idx.object id idxcol.object ...

sql server 查詢欄位上的約束

1.當欄位沒有預設值或者約束的時候可以使用 alter table table name drop column column name 來刪除。當有預設值的時候應該先刪除預設值,然後再刪除此列,不然會報錯。具體方法如下 select b.name from sysobjects b join sy...