Domanda

I have two tables. The table structure is given below.

CREATE TABLE t1
(
     col1 int PRIMARY KEY,
     col2 int REFERENCES t2(col4)
)

And

CREATE TABLE t2
(
     col3 int PRIMARY KEY,
     col4 int REFERENCES t1(col1)
)

Now how do I populate the tables using INSERT statement. I can do it by inserting a NULL value in the FOREIGN KEY COLUMN and then UPDATE that column. But I don't want to use the UPDATE statement. I want to do it using a INSERT statement.

How should I do it?

È stato utile?

Soluzione

I sense a bad design decision here. If update is not an option, then disabling the constraint, inserting data and then re-enabling the constraint can be considered, but that is also an inherently bad approach, as the very purpose of enforcing those constraints in the first place is defeated.

Anyway, here is how:

ALTER TABLE t1 NOCHECK CONSTRAINT <YourFKConstraint>
ALTER TABLE t2 NOCHECK CONSTRAINT <YourFKConstraint>
GO
INSERT INTO t1
VALUES (1,1)
GO
INSERT INTO t2
VALUES (1,1)
GO
ALTER TABLE t1 CHECK CONSTRAINT <YourFKConstraint>
ALTER TABLE t2 CHECK CONSTRAINT <YourFKConstraint>

Please be warned that this approach will allow you to enter data that violates the constraint. Redesign would be the best option.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top