如何删除FB和所有相关表条目?

时间:2010-09-01 14:26:27

标签: sql sql-server tsql foreign-keys constraints

情况就是这样。 有3个表 - 州,地区和城市。如果我删除名为“France”的州,我希望删除属于该州的所有地区和城市。如何在T-SQL中执行此操作?

4 个答案:

答案 0 :(得分:3)

虽然Cascade-Delete是去这里的方式,但我很不高兴。感觉这是一件非常不安全的事情,所以我从未设置过级联删除。

我更喜欢在TSQL中执行此操作

DELETE FROM Cities
WHERE RegionId IN 
(
    SELECT Id
    From Regions
    Where CountryId IN
    (
        Select Id
        From Country
        Where Country = 'France'
    )
)

然后删除区域

DELETE FROM Regions
Where RegionId IN
(
    Select Id
    From Country
    Where Country = 'France'
)

然后删除国家/地区

DELETE FROM Country
Where Country = 'France'

答案 1 :(得分:2)

最简单的解决方案是确保在表之间的关系上启用Cascade Delete。

Create Table State
(
    Code char(2) not null Primary Key
    , ...
)
Create Table Region
(
    Code varchar(10) not null
    , StateCode char(2) not null
    , Constraint FK_Region_State 
        Foreign Key ( StateCode )
        References State( Code )
        On Delete Cascade
)
Create Table City
(
    Name varchar(40) not null
    , StateCode char(2) not null
    , RegionCode varchar(10) not null
    , Constraint FK_City_State 
        Foreign Key ( StateCode )
        References State( Code )
        On Delete Cascade
    , Constraint FK_City_Region
        Foreign Key ( StateCode )
        References State( Code )
        On Delete Cascade
)

如果由于某种原因您无法启用级联删除,则必须通过状态表上的触发器强制执行此规则。 (顺便说一句,一个名为法国的“国家”?)

答案 2 :(得分:2)

我假设你没有设置cascading deletes,所以你必须自下而上:首先删除城市,然后删除区域,然后删除状态。

delete from c
    from city c
        inner join region r
            on c.region_id = r.region_id
        inner join state s
            on r.state_id = s.state_id
    where s.state = 'France'

delete from r
    from region r
        inner join state s
            on r.state_id = s.state_id
    where s.state = 'France'

delete from s
    from state s
    where s.state = 'France'

答案 3 :(得分:0)

您可以设置表格以进行级联删除,因此您可以从表格中删除所有外键输入的条目。