使用SQL约束删除数据

时间:2016-06-21 12:14:44

标签: sql-server

我有以下内容:

DELETE FROM ContactBase
DELETE FROM AccountBase

错误:

The DELETE statement conflicted with the REFERENCE constraint "account_primary_contact". The conflict occurred in database "BMBLANK_MSCRM", table "dbo.AccountBase", column 'PrimaryContactId'.
The DELETE statement conflicted with the REFERENCE constraint "account_contacts". The conflict occurred in database "BMBLANK_MSCRM", table "dbo.ContactBase", column 'AccountId'.

我理解,因为我需要以特定顺序删除数据,但如果我将其反转:

DELETE FROM AccountBase
DELETE FROM ContactBase

它只是反转错误消息:

The DELETE statement conflicted with the REFERENCE constraint "account_contacts". The conflict occurred in database "BMBLANK_MSCRM", table "dbo.ContactBase", column 'AccountId'.
The DELETE statement conflicted with the REFERENCE constraint "account_primary_contact". The conflict occurred in database "BMBLANK_MSCRM", table "dbo.AccountBase", column 'PrimaryContactId'.

如何清空这些表?

由于

3 个答案:

答案 0 :(得分:1)

您可以生成约束的脚本,删除约束,从表中删除,然后使用脚本重新创建约束。

https://jsfiddle.net/DTcHh/21979/

答案 1 :(得分:1)

删除约束,然后从表中删除数据。然后,如果需要,再次添加约束。

答案 2 :(得分:1)

首先删除约束,删除数据并再次添加:

ALTER TABLE AccountBase
  DROP CONSTRAINT account_contacts;

ALTER TABLE ContactBase
  DROP CONSTRAINT account_primary_contact;

DELETE FROM ContactBase;
DELETE FROM AccountBase;

ALTER TABLE AccountBase
ADD FOREIGN KEY (account_contacts)
REFERENCES ContactBase(PrimaryContactId);

ALTER TABLE ContactBase
ADD FOREIGN KEY (account_primary_contact)
REFERENCES AccountBase(AccountId);

也许我把它们混合在一起,如果没有表DDL的话会让人感到困惑,所以如果我只是调整它。