我有一组表(SQL Server 2014),我需要手动执行删除级联。我有这三个表:
CREATE TABLE dbo.A
(
IdKey int identity primary Key,
Name nvarchar(50)
)
CREATE TABLE dbo.B
(
Id int identity primary Key,
ChildIdKey int,
Name nvarchar(50)
)
CREATE TABLE dbo.C
(
Id int identity primary Key,
OtherIdKey int,
Name nvarchar(50)
)
如果我需要从表A中删除IdKey,我首先需要识别表A上指向IdKey的外键。我在表B上有一个基于ChildIdKey的FK,另一个在表C上有另一个在FK上的OtherIdKey上。列名是不同所以现在我需要得到所有表格,我有一个FK指向IdKey并手动执行删除级联,以避免FK错误。
如何以正确的顺序获取表格列表以手动执行级联删除?
答案 0 :(得分:0)
尝试根据some-table
的特定列找出所有表DECLARE @ColumnName sysname,@TableName sysname
SET @ColumnName='userId'
SET @TableName='user'
SELECT Fkn.name FKName ,
cname.name FKColumnName,
FCT.name FKContainingTable ,
CCT.name ColumnContainingTable
FROM sys.foreign_key_columns Fk
INNER JOIN sys.foreign_keys fkn ON fkn.object_id=fk.constraint_object_id
INNER JOIN sys.tables FCT ON fCt.object_id = fk.parent_object_id
INNER JOIN sys.tables CCT ON fk.referenced_object_id = CCT.object_id
INNER JOIN sys.columns CLM ON CCT.object_id = clm.object_id
INNER JOIN sys.columns CName ON CName.object_id=fk.parent_object_id AND CName.column_id=fk.parent_column_id
AND CLM.name = @ColumnName
AND cct.name = @TableName