Adding self-conflict conflicts, although it does not exist yet

I am adding cascade deletion to the table. The table Clonehas a column DeviceID, which is the foreign key in the Devicetable column DeviceID. Thus, the SQL script resets the original FK constraint and tries to add a new one:

IF EXISTS
(
    SELECT *
    FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
    WHERE CONSTRAINT_NAME = 'FK_Clone_Device'
)
BEGIN
    ALTER TABLE Clone
    DROP CONSTRAINT FK_Clone_Device
END

IF NOT EXISTS
(
    SELECT *
    FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
    WHERE CONSTRAINT_NAME = 'FK_Clone_Device_Cascade'
)
BEGIN
    ALTER TABLE Clone
    ADD CONSTRAINT FK_Clone_Device_Cascade
    FOREIGN KEY (DeviceID) REFERENCES Device(DeviceID) ON DELETE CASCADE
END

When I run this script, I get the following error:

 The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_Clone_Device_Cascade". The conflict occurred in database "DevelopmentDB", table "dbo.Device", column 'DeviceID'.

Perhaps I misunderstand the error message, but it seems to be contradicting itself. I am confused by the fact that this happened on the table Device.

The table Clonehas an index at DeviceID. Will it be important?

This is on SQL SERVER R2 (Azure)

+4
source share
1 answer

, , FK, . - "WITH (NOCHECK)" ALTER TABLE , .

NOCHECK, , / , FK.

, :

ALTER TABLE Clone WITH NOCHECK
ADD CONSTRAINT FK_Clone_Device_Cascade
FOREIGN KEY (DeviceID) REFERENCES Device(DeviceID) ON DELETE CASCADE
+7

Source: https://habr.com/ru/post/1568202/


All Articles