先看看我们要用到的几个目录视图的解释:
1,sys.foreign_keys--在这个视图中返回了所有的外键约束
2,sys.foreign_key_columns--在这个视图中返回了所有外键列(只返回列的id)
3,sys.columns--在这个视图中返回了表与视图的所有列
示例:
比如我们要查询表tb1的所有外键信息,代码如下:
select
a.name as 约束名,
object_name(b.parent_object_id) as 外键表,
d.name as 外键列,
object_name(b.referenced_object_id) as 主健表,
c.name as 主键列
from sys.foreign_keys A
inner join sys.foreign_key_columns B on A.object_id=b.constraint_object_id
inner join sys.columns C on B.parent_object_id=C.object_id and B.parent_column_id=C.column_id
inner join sys.columns D on B.referenced_object_id=d.object_id and B.referenced_column_id=D.column_id
where object_name(B.referenced_object_id)='tb1';