Click here to Skip to main content
15,888,454 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hi
need some help with my code...I need to insert into two tables

DECLARE @IDENTITY INT
INSERT INTO BestallningMatratt (MatrattID,BestallningID, Antal) VALUES ('1','2','3')
SELECT @IDENTITY = @@IDENTITY FROM BestallningMatratt
INSERT INTO Bestallning(BestallningID,BestallningDatum,Totalbelopp,Levererad,KundID) VALUES (@IDENTITY,'28-02-2014','250','1','1')


I get error when I run my code

Msg 547, Level 16, State 0, Line 2
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_BestallningMatratt_Bestallning". The conflict occurred in database "Tomasos", table "dbo.Bestallning", column 'BestallningID'.
The statement has been terminated.
Msg 544, Level 16, State 1, Line 4
Cannot insert explicit value for identity column in table 'Bestallning' when IDENTITY_INSERT is set to OFF.
Posted

1 solution

do your insert into bestallning
then select SCOPE_IDENTITY() into a var
then insert into your other table.

it also looks like the join table you have, bestallningmartratt has FK into bestallning so your commands wont work in that order regardless of what you do about the identity column.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900