我需要在 SQL Server 数据库中删除一个高度引用的表。我如何获取要删除表需要删除的所有外键约束的列表?
(与在 Management Studio 的 GUI 中单击相比,SQL 回答更可取。)
不知道为什么没有人建议,但是我使用sp_fkeys
查询给定表的外键:
EXEC sp_fkeys 'TableName'
您还可以指定架构:
EXEC sp_fkeys @pktable_name = 'TableName', @pktable_owner = 'dbo'
在未指定架构的情况下, 文档规定以下内容:
如果未指定 pktable_owner,则适用基础 DBMS 的默认表可见性规则。
在 SQL Server 中,如果当前用户拥有具有指定名称的表,则将返回该表的列。如果未指定 pktable_owner 且当前用户不拥有具有指定 pktable_name 的表,则该过程将查找数据库所有者拥有的具有指定 pktable_name 的表。如果存在,则返回该表的列。
我会使用 SQL Server Management Studio 中的数据库图表功能,但是由于您排除了这一点,所以这在 SQL Server 2008(没有 2005)中对我有用。
要获取引用表和列名称的列表...
select
t.name as TableWithForeignKey,
fk.constraint_column_id as FK_PartNo, c.
name as ForeignKeyColumn
from
sys.foreign_key_columns as fk
inner join
sys.tables as t on fk.parent_object_id = t.object_id
inner join
sys.columns as c on fk.parent_object_id = c.object_id and fk.parent_column_id = c.column_id
where
fk.referenced_object_id = (select object_id
from sys.tables
where name = 'TableOthersForeignKeyInto')
order by
TableWithForeignKey, FK_PartNo
获取外键约束的名称
select distinct name from sys.objects where object_id in
( select fk.constraint_object_id from sys.foreign_key_columns as fk
where fk.referenced_object_id =
(select object_id from sys.tables where name = 'TableOthersForeignKeyInto')
)
这给您:
代码如下:
SELECT obj.name AS FK_NAME,
sch.name AS [schema_name],
tab1.name AS [table],
col1.name AS [column],
tab2.name AS [referenced_table],
col2.name AS [referenced_column]
FROM sys.foreign_key_columns fkc
INNER JOIN sys.objects obj
ON obj.object_id = fkc.constraint_object_id
INNER JOIN sys.tables tab1
ON tab1.object_id = fkc.parent_object_id
INNER JOIN sys.schemas sch
ON tab1.schema_id = sch.schema_id
INNER JOIN sys.columns col1
ON col1.column_id = parent_column_id AND col1.object_id = tab1.object_id
INNER JOIN sys.tables tab2
ON tab2.object_id = fkc.referenced_object_id
INNER JOIN sys.columns col2
ON col2.column_id = referenced_column_id AND col2.object_id = tab2.object_id