Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 Insert query pk and FK issue!!

Author  Topic 

agarwasa2008
Posting Yak Master

109 Posts

Posted - 2009-10-28 : 19:07:06
Hi,

I have a table1:
ID(FK,varchar(1),not null)
desc

Table2:
ID(PK,varchar(1),not null)
col1
col2

I want to run an sql query but it gives the following error:
SQL Query:

insert into table1 (id, desc)
select * from table3

Error msg:
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_tabl1_table2". The conflict occurred in database "test", table "dbo.table2", column 'id'.
The statement has been terminated.


SA

DeveloperIQ
Yak Posting Veteran

71 Posts

Posted - 2009-10-28 : 19:10:13
Make sure that the values you are inserting into the ID field of Table 1 already exist in the ID field of Table 2
Go to Top of Page

agarwasa2008
Posting Yak Master

109 Posts

Posted - 2009-10-28 : 19:19:46
okay. If the values exists the insert should have no issues. Right!

SA
Go to Top of Page

DeveloperIQ
Yak Posting Veteran

71 Posts

Posted - 2009-10-28 : 19:22:43
Right
Go to Top of Page

agarwasa2008
Posting Yak Master

109 Posts

Posted - 2009-10-28 : 19:26:36
Thanks!!

But I do have 2 values that is causing the insert to not work. How can I eliminate those 2 value.

SA
Go to Top of Page

DeveloperIQ
Yak Posting Veteran

71 Posts

Posted - 2009-10-28 : 19:35:24
Assuming table3 has some ID field as well, you can do something like this:
insert into table1 (id, desc)
select table3.* from table3 join
table2 on table3.ID = table2.ID
Go to Top of Page
   

- Advertisement -