从依赖表中删除数据

时间:2010-09-20 10:59:38

标签: sql sql-server tsql sql-server-2008

SQL Server 2008中是否有一个查询,它将删除所有相关表中的数据以及所选表格?

我很抱歉没有详细说明这个问题。我知道Cascade Delete可以正常工作,但我的应用程序连接到第三方SQL Server数据库。我有一些单元测试插入到目标表和从属表中。不幸的是,目标表上的约束不是On Delete Cascade,我无法创建它们或创建它们。我正在寻找一种遍历依赖关系并以正确顺序删除数据的通用方法。

3 个答案:

答案 0 :(得分:7)

由于外键关系,以下脚本可以让您开始模仿级联删除。

DECLARE @TableName VARCHAR(32)
DECLARE @PrimaryKey VARCHAR(32)

SET @TableName = 'MasterTable'
SET @PrimaryKey = '1'

SELECT  'DELETE FROM '
        + fks.name + '.' + fkt.name
        + ' WHERE '
        + pc.name 
        + ' = '
        + @PrimaryKey
        , fko.name as [FK Name]
        , fk.constraint_column_id as [Col Order]
        , fks.name + '.' + fkt.name as [FK table]
        , pc.name as [FK column]
        , rcs.name + '.' + rct.name as [PK table]
        , rc.name as [PK column]
FROM    sys.foreign_key_columns fk
        -- FK columns
        INNER JOIN sys.columns pc ON fk.parent_object_id = pc.object_id
                                     AND fk.parent_column_id = pc.column_id
        INNER JOIN sys.objects fkt ON pc.object_id = fkt.object_id
        INNER JOIN sys.schemas as fks ON fks.schema_id = fkt.schema_id
        -- referenced PK columns
        INNER JOIN sys.columns rc ON fk.referenced_object_id = rc.object_id
                                     AND fk.referenced_column_id = rc.column_id
        INNER JOIN sys.objects rct ON rc.object_id = rct.object_id
        INNER JOIN sys.schemas as rcs ON rcs.schema_id = rct.schema_id
        -- foreign key constraint name
        INNER JOIN sys.objects fko ON fk.constraint_object_id = fko.object_id
WHERE   rct.Name = @TableName

答案 1 :(得分:2)

为此,您可以使用级联删除在表之间设置约束。您可以通过拖动字段之间的连接并编辑属性或使用查询来在图表中执行此操作:

 alter table SomeTable
 add constraint SomeConstraint
 foreign key (SomeField) references SomeOtherTable (SomeOtherField) 
 on delete cascade

答案 2 :(得分:1)

从msdn,书籍,文章中了解ON CASCADE DELETE,您将找到答案。

Cascading Referential Integrity Constraints