I have a broken foreign key in SQL Server 2005. Here is a reproduction:
CREATE TABLE t2(i2 BIGINT NOT NULL PRIMARY KEY)
CREATE TABLE t1(i1 BIGINT NOT NULL PRIMARY KEY)
ALTER TABLE t1 ADD CONSTRAINT fk FOREIGN KEY (i1) REFERENCES t2 (i2)
ALTER TABLE t1 NOCHECK CONSTRAINT fk
INSERT INTO t1 (i1) VALUES (0)
If I subsequently run:
ALTER TABLE t1 WITH CHECK CHECK CONSTRAINT fk
I get the error:
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "fk". The conflict occurred in database "broken-fk", table "dbo.t2", column 'i2'.
I can fix this manually:
DELETE FROM t1 WHERE NOT EXISTS (SELECT 1 FROM t2 WHERE t2.i2 = t1.i1)
ALTER TABLE t1 WITH CHECK CHECK CONSTRAINT fk
but I'd prefer to do it in one step, as each presumably needs a table scan and the table is tens of gigabytes in size.
Is it possible to get the ALTER TABLE to fix the error (by dropping rows) rather than exiting with an error?
Thanks.