gpt4 book ai didi

sql - 从SQL 2008中的外键关系生成删除语句?

转载 作者:行者123 更新时间:2023-12-03 12:31:18 24 4
gpt4 key购买 nike

是否可以通过脚本/工具基于表fk关系生成删除语句。

即我有表:DelMe(ID),有30个表,首先需要删除对其ID的fk引用,是否可以运行一些工具/脚本,它们将基于FK关系生成30个delete语句为了我 ?

(顺便说一句,我知道有关关系的级联删除,我不能在此现有数据库中使用它)

我正在使用Microsoft SQL Server 2008

最佳答案

生成的DELETE语句,用于带参数的SP以及ON DELETE触发器:
(此变体仅支持单列FK)

SELECT 'DELETE '+detail.name+' WHERE '+dcolumn.name+' = @'+mcolumn.name AS stmt, 
'DELETE ' + detail.name + ' FROM ' + detail.name + ' INNER JOIN deleted ON ' +
detail.name + '.' + dcolumn.name + ' = deleted.' + mcolumn.name AS trg
FROM sys.columns AS mcolumn
INNER JOIN sys.foreign_key_columns ON mcolumn.object_id =
sys.foreign_key_columns.referenced_object_id
AND mcolumn.column_id = sys.foreign_key_columns.referenced_column_id
INNER JOIN sys.tables AS master ON mcolumn.object_id = master.object_id
INNER JOIN sys.columns AS dcolumn
ON sys.foreign_key_columns.parent_object_id = dcolumn.object_id
AND sys.foreign_key_columns.parent_column_id = dcolumn.column_id
INNER JOIN sys.tables AS detail ON dcolumn.object_id = detail.object_id
WHERE (master.name = N'MyTableName')

关于sql - 从SQL 2008中的外键关系生成删除语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/485581/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com