SQL Constraint-Insert Fails - sql-server

I have two table table1 and table2. I have a record in table1. I want to insert record into table2. but it comes up with the following Exception.
Msg 547, Level 16, State 0, Line 2
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Table2_<Column3>". The conflict occurred in database "<databaseName>", table "table1", column 'Id'.
The constraint on the table2 is like this.
ALTER TABLE [dbo].[table2] ADD CONSTRAINT [DF__table2__name__0B91BA14] DEFAULT ((0)) FOR [column4]

The error shows that you also have a foreign key constraint and you are trying to insert a row into a child table that doesn't have corresponding record in master

The exception message is telling you which constraint is causing the issue. It's against Column3 (at least that's what the name suggests) and is a foreign key constraint against table1.
You're not showing any sample SQL but it would appear you're trying to insert data in to table2 where the foreign key value specified for Column3 does not exist in table1.

Your Comment helped me.
I have used this Query to insert data into the new database from the old databse.
INSERT INTO Database.[dbo].[Table2] ([colmn1]
,[colmn2]
,[colmn3]
,[columns4]
)
SELECT [colmn1]
,[colmn2]
,[colmn3]
,[columns4]
FROM [OtherDatabase].[dbo].[Table2]
But there is a constarint on colum3 which is foreign key on Table1.
I have changed the colmn3 of table1 to same Guid as otherDatabase Guid and it works.
Thanks All

Related

How to create connection between two tables in SQL Server 2008?

I have database that has Student table with information about each student in the system. Each record in that table has unique identifier that was created with NEWID() in SQL 2008. Then I have three other tables that use the same ID to link the student and the record. I'm wondering if I need to set any kind of property that will link these tables/records. Here is example of my Student table:
st_id -> Auto increment id
st_studentGUID -> Primary key
st_firstName
st_lastName
st_dob
st_gender
st_uid
st_udt
st_utime
And here is example of my other three tables:
Table 1 Table 2 Table 3
tb1_id -> auto increment tb2_id -> auto increment tb3_id -> auto increment
tb1_studentGUID tb2_studentGUID tb3_studentGUID
I have tried to create foreign key for each Table 1,2 and 3 on studentGUID but I got an error:
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_Table1_Student". The conflict occurred in database "testDB", table "Student", column 'st_studentGUID'.
After I have done some research seems like this error occurred because Table 1 doesn't have all st_studentGUID. This make sense because student record might exist in Table 3 but not in Table 1. I'm wondering if there is any other sort of relation that I can set between the tables? Should I maybe use the Indexes on studentGUID fields? This is the reason why I'm asking this, in one of my update queries I use auto incremented id in where clause and for some reason I received an error that looks like this:
ErrorCode 1205
Message [Macromedia][SQLServer JDBC Driver][SQLServer]Transaction (Process ID 111) was deadlocked on lock | communication buffer resources with another process and has been chosen as the deadlock victim. Rerun the transaction.
SQLState 40001
and error was pointing to the line that is end of the update query that looks like this:
<cfquery name="updateTable1" datasource="testDB">
UPDATE Table1
SET
tb1_testdt = <cfqueryparam value="#FORM.frm_testdt#" cfsqltype="cf_sql_date" maxlength="10" null="#yesNoFormat(!len(FORM.frmhs_testdtgr))#" />
FROM Table1 AS Table
LEFT OUTER JOIN studentLocked AS Locked
ON Locked.lk_studentGUID = Table.tb1_studentGUID
WHERE tb1_id = <cfqueryparam value="#FORM.frm_id#" cfsqltype="cf_sql_integer" />
AND lk_active = '1'
AND lk_staffID = <cfqueryparam value="#trim(appStaff)#" cfsqltype="cf_sql_char" maxlength="10" />
</cfquery>
Query above is checking if studentGUID exists in Lock table, reason why I'm doing this is because we do not want two different users updating the same record at the same time. Query updates single record and should be pretty fast. I'm confused whit the error message above deadlock victim. Is there something in my database design that is off or my update query is causing this error? I couldn't find anything on the web that could help me fix this issue. if anyone has experience with this kind of problem please let me know.
If all StudentGUIDs exist in the Student table, then the correct design is to have the StudentGUID in Table1, Table2 and Table3 be a Foreign Key to the Student table.
Now that you've sorted out your foreign key issue with the missing record from Student, try setting up your FKs on all of your tables, then re-try your update query.
If the deadlock issue persists and is reproducible, submit a new question for that, including the schema for the table you're updating and the values you're trying to pass.
Here's a script that demonstrates you can create the relationships you described provided all the keys are present in the students table:
CREATE TABLE students (st_id AS NEWID(),
st_studentGUID UNIQUEIDENTIFIER PRIMARY KEY)
INSERT INTO students (st_studentGUID) VALUES ('3B9F59DD-BF0A-4A09-BF4E-A396E2978B24')
INSERT INTO students (st_studentGUID) VALUES ('7CC5FF67-DAB8-426A-B9F7-E9F041718B6B')
INSERT INTO students (st_studentGUID) VALUES ('84B80D3E-44C4-4291-857D-B6CA6552369D')
CREATE TABLE t1 (tb1_id AS NEWID(), tb1_studentGUID UNIQUEIDENTIFIER)
ALTER TABLE t1
ADD CONSTRAINT FK_t1_tbl_studentGUID FOREIGN KEY (tb1_studentGUID) REFERENCES students(st_studentGUID)
INSERT INTO t1 (tb1_studentGUID) VALUES ('3B9F59DD-BF0A-4A09-BF4E-A396E2978B24')
CREATE TABLE t2 (tb2_id AS NEWID(), tb2_studentGUID UNIQUEIDENTIFIER)
ALTER TABLE t2
ADD CONSTRAINT FK_t2_tbl_studentGUID FOREIGN KEY (tb2_studentGUID) REFERENCES students(st_studentGUID)
INSERT INTO t2 (tb2_studentGUID) VALUES ('7CC5FF67-DAB8-426A-B9F7-E9F041718B6B')
CREATE TABLE t3 (tb3_id AS NEWID(), tb3_studentGUID UNIQUEIDENTIFIER)
ALTER TABLE t3
ADD CONSTRAINT FK_t3_tbl_studentGUID FOREIGN KEY (tb3_studentGUID) REFERENCES students(st_studentGUID)
INSERT INTO t3 (tb3_studentGUID) VALUES ('84B80D3E-44C4-4291-857D-B6CA6552369D')
Now create a 4th table, add a UUID that isn't in the students table, and try to create the foreign key constraint:
CREATE TABLE t4 (tb4_id AS NEWID(), tb4_studentGUID UNIQUEIDENTIFIER)
INSERT INTO t4 (tb4_studentGUID) VALUES ('897925F1-BE92-44EB-82C3-88E1C33C7792')
ALTER TABLE t4
ADD CONSTRAINT FK_t4_tbl_studentGUID FOREIGN KEY (tb4_studentGUID) REFERENCES students(st_studentGUID)
Which reproduces your error message:
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_t4_tbl_studentGUID". The conflict occurred in database "IconERP", table "dbo.students", column 'st_studentGUID'.

Error while adding a foreign key constraint

Msg 547, Level 16, State 0, Line 2
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint
"AB_TRANS_FK3". The conflict occurred in database "DEV", table
"dbo.PRODUCT", column 'ID'.
Hello all,
I need your help with this error. I am trying to add a foreign key constraint here using the following query
ALTER TABLE [dbo].[AB_TRANS] WITH CHECK ADD CONSTRAINT [AB_TRANS_FK3] FOREIGN KEY([ID])
REFERENCES [dbo].[PRODUCT] ([ID])
Check your table to see which row(s) are causing the issue, then you'll need to fix them. This should help:
SELECT *
FROM
dbo.AB_Trans A
WHERE
NOT EXISTS (SELECT * FROM dbo.Product P WHERE P.ID = A.ID)
If there isn't a match, are you using "0" for the ID or some other dummy value? This could certainly cause the problem as you should be using NULL in those cases.

Insert records from one table to another without violating any constraint in SQL Server database

There are 2 databases DB_Main and DB_Backup in SQL Server 2008.
I want to copy the data of Table1 from DB_Backup into Table1 of DB_Main.
The structure of all the tables in both the database is same. Both the tables in both the database have foreign key, primary key constraint.
When I try to copy data of Table1 from DB_Backup into Table1 of DB_Main with this query:
Insert into [DB_Main].[Table1]
Select *
from [DB_Backup].[Table1];
I get this foreign key error.
The INSERT statement conflicted with the FOREIGN KEY constraint
"FK_Table1_Table3". The conflict occurred in database "DB_Main",
table "Table3", column 'RequestID'.
Please let me know any simple way to copy all the records of Table1 from DB_Backup into Table1 of DB_Main, without violating any constraint?
Please reply
What this means is that for example you are trying to insert a record into Table1 which has for example RequestID = 75. The foreign key constraint means that there must be a record with RequestID = 75 in Table3.... and there currently isn't.
So this means you also need to load data into Table3
To find the records actually causing the issue run
Select DISTINCT RequestID from [DB_Backup].[Table1]
Some of these request ID's need a 'parent' record in Table3
To find the specific ones run
Select RequestID from [DB_Main].[Table3]
WHERE Request_ID NOT IN (
Select DISTINCT RequestID from [DB_Backup].[Table1]
)
You need to insert these into Table3:
insert into Table3(Request_ID, OtherColumn)
Select RequestID, OtherColumn from [DB_Backup].[Table3]
WHERE Request_ID NOT IN (
Select DISTINCT RequestID from [DB_Main].[Table3]
)
Then you can load your other records.
Drop or Disable constraint FK_Table1_Table3 before inserting and enable after it.
To Disable:
ALTER TABLE Table1 NOCHECK CONSTRAINT ALL
or
ALTER TABLE Table1 NOCHECK CONSTRAINT FK_Table1_Table3
Source
to Enable
ALTER TABLE Table1 CHECK CONSTRAINT ALL
or
ALTER TABLE Table1 CHECK CONSTRAINT FK_Table1_Table3

sql - update two key columns without conflict

I want to to update a column from table patient, and add a prefix before all its fields, like
update patient
set contactdetailsID = '99999'+ contactdetailsID
where patient.id = 5294
So, row with id = 5294, will have the same value in column contactdetailsID with prefix 99999.
Before | After
012345 99999012345
the issue i am facing is that patient.contactdetailsID is the foreign key for another table "contactdetails".
So i get the following error.
Msg 547, Level 16, State 0, Line 1 UPDATE statement conflicted with
COLUMN FOREIGN KEY constraint 'ContactDetails_Patient_FK1'. The
conflict occurred in database 'A', table 'ContactDetails',
column 'id'. The statement has been terminated.
(0 row(s) affected)
How can i make that change? I want to change both patient.contactdetailsID and its key Contactdetails.ID, with the same prefix in order not to lose the connection between them.
You can temporary disable the Foreign-Key Constraint using:
ALTER TABLE *Tablename*
NOCHECK CONSTRAINT *ForeinKey_Name*;
and update both the ContactDetails Table and Patient Table.
But make sure that you enable the ForeignKey afterwards!
To enable a Foreign Key use
ALTER TABLE *Tablename*
CHECK CONSTRAINT *ForeinKey_Name*;
You could implement ON UPDATE CASCADE in your table.
see MySQL documentation

Unable to get a Foreign key

USE Kudler_FF
ALTER TABLE Employee_Tbl
ADD CONSTRAINT FK_Employee_Tbl
FOREIGN KEY (JobTitle) REFERENCES Job_Tbl (JobTitle);
Message I am getting:
Msg 547, Level 16, State 0, Line 2
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_Employee_Tbl". The
conflict occurred in database "Kudler_FF", table "dbo.Job_Tbl", column
'JobTitle'.
What did I add or not add
You usually only get an error adding a foreign key constraint when the constraint would be violated by the current data.
In other words, you probably have a value in Employee_Tbl(JobTitle) that does not exist in Job_Tbl(JobTitle).
You would not be able to add such a constraint until your data is modified so that a violation would not occur.
Find the values for JobTitle in Employee_Tbl that don't exist in Job_Tbl and then add them to that latter table.
I'm not sure of the exact syntax for SQL Server but you could start with:
select distinct JobTitle from Employee_Tbl
where JobTitle not in (
select distinct JobTitle from Job_Tbl
)

Resources