关于sql server:使用Inner join进行DELETING

DELETING using Inner join

我遵循了如何执行删除自:如何使用与SQL Server的内部联接来删除?

要删除的数据:

1
2
3
4
5
6
7
  select * from com.Address a
  inner join com.Contact as c on c.AddressId = a.AddressId
  inner join cqt.CQMTrainer as t on t.ContactId = c.ContactId


 select from com.Contact c
  inner join cqt.CQMTrainer as t on t.ContactId = c.ContactId

下面是我尝试执行的删除操作:

1
2
3
4
5
6
  delete a from com.Address a
  inner join com.Contact as c on c.AddressId = a.AddressId
  inner join cqt.CQMTrainer as t on t.ContactId = c.ContactId

  delete c from com.Contact c
  inner join cqt.CQMTrainer as t on t.ContactId = c.ContactId

但是,一旦我执行它们,就会出现一些外键错误:

The DELETE statement conflicted with the REFERENCE constraint
"FK_com.Contact_com.Address_AddressId". The conflict occurred in
database"", table"com.Contact", column 'AddressId'.

我在错误地跟踪什么?我甚至尝试添加begin transactioncommit transaction


如果你用另一种方式做呢:

1
2
3
4
5
6
delete c from com.Contact c
inner join cqt.CQMTrainer as t on t.ContactId = c.ContactId

delete a from com.Address a
inner join com.Contact as c on c.AddressId = a.AddressId
inner join cqt.CQMTrainer as t on t.ContactId = c.ContactId
  • 首先,您将删除联系人表上的信息作为错误说您在联系人上有地址ID的引用,这就是为什么您不能先删除地址表的原因。

查看查询时,您的关系已配置为在尝试删除另一条引用的记录时引发异常。如果要避免这种情况,必须选择数据库服务器应该如何处理这种情况。这是在引用属性上设置的。如果使用的是SQL Server Management Studio,则:

  • 用鼠标右键单击表格选择"设计"
  • 然后定义关系的列(它将显示为行)
  • 然后用鼠标右键单击列您感兴趣,请选择"关系"
  • 然后在左窗格中按名称查找关系,单击它
  • 然后在右窗格中,您将发送"insert and update"规格组,展开
  • 然后您将找到两个规则,一个用于更新,一个用于删除,您可以选择:

    • 不采取行动-像在你的案例中那样抛出异常
    • cascade-删除引用行
    • 设置空值-将在FK值引用此行的行中设置空值
    • 设置默认值-将设置此类列的默认值。
  • 如果不使用这种编辑器,可以在

    1
    REFERENCES TableName ColumnName

    价值观如下:

    1
    ON DELETE  { NO ACTION | CASCADE | SET NULL | SET DEFAULT }