Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No way to use TSQL Output with normal foreign key constraints?

Tags:

tsql

The following snippet fails with error:

The target table 'dbo.forn' of the OUTPUT INTO clause cannot be on either side of a (primary key, foreign key) relationship. Found reference constraint 'FK_forn_prim'."

I can only use output by disabling foreign key constraints? How can this be done?

IF OBJECT_ID ('dbo.forn') IS NOT NULL
begin
    alter table dbo.forn drop constraint FK_forn_prim
    DROP TABLE dbo.forn;
end
IF OBJECT_ID ('dbo.prim') IS NOT NULL
    DROP TABLE dbo.prim;
go

CREATE TABLE dbo.prim (c1 int PRIMARY KEY);
CREATE TABLE dbo.forn (c1 int CONSTRAINT FK_forn_prim FOREIGN KEY (c1) REFERENCES dbo.prim(c1));
go

INSERT INTO dbo.prim
    OUTPUT inserted.c1 INTO dbo.forn
SELECT 1;
like image 884
dudeNumber4 Avatar asked Jul 27 '10 14:07

dudeNumber4


People also ask

How do you bypass a foreign key constraint?

Use SQL Server Management StudioIn Object Explorer, expand the table with the constraint and then expand the Keys folder. Right-click the constraint and select Modify. In the grid under Table Designer, select Enforce Foreign Key Constraint and select No from the drop-down menu. Select Close.

How do I reference a foreign key in SQL?

Using SQL Server Management Studio Open the Table Designer for the table containing the foreign key you want to view, right-click in the Table Designer, and choose Relationships from the shortcut menu. In the Foreign Key Relationships dialog box, select the relationship with properties you want to view.

How do I fix foreign key constraint failure?

The error message itself showing there is a foreign key constraint error, which means you are deleting a parent table where the child table contains the Primary table identifier as a foreign key. To avoid this error, you need to delete child table records first and after that the parent table record.

Can a foreign key have a default value?

Yes, you can define a column with a default value of 0 as a Foreign Key. However, for the constraint to work, you would need to have a row in the source table with a value of 0 as well. Example: CREATE TABLE dbo.


2 Answers

Normally you output to a table variable or temp table, then use that to insert to the final table.

like image 73
HLGEM Avatar answered Nov 16 '22 13:11

HLGEM


You're correct, output statements won't work on tables under foreign key constraints.

Another option would be to temporarily disable the constraints while you insert the data. Though this shouldn't be the norm, it works well for one time loads of data.

ALTER TABLE dbo.forn
NOCHECK CONSTRAINT FK_forn_prim
GO

INSERT INTO dbo.prim
    OUTPUT inserted.c1 INTO dbo.forn
SELECT 1;

ALTER TABLE dbo.forn
CHECK CONSTRAINT FK_forn_prim
GO
like image 32
Jeremy Jarrell Avatar answered Nov 16 '22 14:11

Jeremy Jarrell