Unable to add foreign key constraint due to obscure conflict - sql

Trying to run :
ALTER TABLE [dbo].[Table1] ADD
CONSTRAINT [FK_Table1_ScenarioResult]
FOREIGN KEY ([ScenarioResultID]) REFERENCES [dbo].[ScenarioResult] ([ScenarioResultID]) ON DELETE CASCADE
Getting this error :
Msg 547, Level 16, State 0, Line 1
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_Table1_ScenarioResult". The conflict occurred in database "8362", table "dbo.ScenarioResult", column 'ScenarioResultID'.
I have checked :
Constraint does not already exist, and no other exists on same column
The values in the column match in both tables
Types of columns are the same
Tried a different name, also fails
On SQL Server 2008 R2
Any ideas what I could try?

In theory this might work:
ALTER TABLE [dbo].[Table1] WITH NOCHECK ADD
CONSTRAINT [FK_Table1_ScenarioResult]
FOREIGN KEY ([ScenarioResultID]) REFERENCES [dbo].[ScenarioResult] ([ScenarioResultID])
ON DELETE CASCADE
Not sure how you checked for integrity of existing values, but it should be:
SELECT COUNT(*) as Orphans FROM [dbo].[Table1] t
WHERE NOT EXISTS
(SELECT * FROM [dbo].[ScenarioResult] WHERE ScenarioResultID = t.ScenarioResultID)
If "Orphans" is greater then zero you need to clean the data before adding a constraint.

This one was baffling me aswell, and then the penny dropped.
I was trying to create a Foreign Key using "Database Diagrams" in SQL Server 2012, but it refused to let me as it claimed to clash with the foreign key I was trying to create. Huh ?
But, I had accepted the defaults to "Enforce foreign key constraint". But I already had data in the two tables I was attempting to create a foreign key for, and it was breaking the foreign key rule I was trying to make, so SQL Server was rejecting the new key.
The solution (in this particular case) was to change "Enforce foreign key constraint" to "No", or at least until I had cleaned up my data.
Hope this helps.

I had the same issue
I clear the data of the tables where i want to edit the content and add a new foreign key constraint and retry.
It works for me.
I hope it help you.

Related

Weird mysql behavior when adding foreign key

I am trying to add a simple foreign key like so
ALTER TABLE `4over4local`.`wf_job_status`
ADD CONSTRAINT `fk_sales_job_status_sales_job1`
FOREIGN KEY (`job_id`)
REFERENCES `4over4local`.`sales_job` (`job_id`)
ON DELETE CASCADE
ON UPDATE CASCADE;
But i am getting a very weird error with some database table named #sql-d74_9 that doesn't even exist.
ERROR 1452: Cannot add or update a child row: a foreign key constraint fails (`4over4local`.`#sql-d74_9`,
CONSTRAINT `fk_sales_job_status_sales_job1` FOREIGN KEY (`job_id`) REFERENCES `sales_job` (`job_id`)
ON DELETE CASCADE ON UPDATE CASCADE)
I have previously made very similar queries and they all worked fine except this one. What could cause this and what i am doing wrong? I am using MariaDB 13
The error indicates that you have rows in the table that do not satisfy the foreign key constraint you are trying to add. You need to fix your data before you can create the constraint.
You can exhibit offending rows with the following query:
select wjs.*
from wf_job_status wjs
where not exists (select 1 from sales_job sj where sj.job_id = wjs.job_id)

While alter table adding foreign key getting error in SQL Server

I am trying to add a foreign key in SQL Server to an existing table, but I'm getting an error. Could any one please help me?
Note: objid is present in both table 1 & table 2
ALTER TABLE table1
ADD CONSTRAINT FK_41_PRICE_INST2PRICE_QTY
FOREIGN KEY (Table1 PRICE_INST2PRICE_QTY) REFERENCES table2(objid);
Error:
FK_40_PRICE_INST2PRICE_QTY. The conflict occurred in database "test", table "dbo.table2", column 'objid'.
Apart from the error in the syntax, I think there are some values in the objid column that doesn't exist in the PRICE_INST2PRICE_QTY table. You have to check the values between the two columns. This is why you are creating the foreign key to prevent such things.
The syntax should be something more like this:
ALTER TABLE table1
ADD CONSTRAINT FK_41_PRICE_INST2PRICE_QTY
FOREIGN KEY (PRICE_INST2PRICE_QTY) REFERENCES table2(objid);
You don't need to qualify the column name.
Do a quick check on you column 'objid' and don't write
FOREIGN KEY (Table1 PRICE_INST2PRICE_QTY) REFERENCES table2(objid);
It should be more like:
FOREIGN KEY (PRICE_INST2PRICE_QTY) REFERENCES table2(objid);
without table1, because you're working in table1.

Firebird: Alter "anonymous" foreign key

I need to alter an existing foreign key from "on delete restrict" to "on delete cascade". Unfortunaltey this bug sneaked through Q/A.
In my database I have several forign key relationships that were automatically named (INTEG_1, INTEG_2, ...). The name of the constraint I have to fix is another in a new installation than in an Update from Version 2 and even another than when this Version 2 previously has been updated from Version 1.
As the referencing table only has one foreign key, this statement gives me the name of the constraint:
SELECT RDB$CONSTRAINT_NAME
FROM RDB$RELATION_CONSTRAINTS
where RDB$CONSTRAINT_TYPE = 'FOREIGN KEY'
and RDB$RELATION_NAME = 'MY_TABLE_NAME'
then I can drop and afterwards recreate the foreign key (with a "real" name this time)
alter table MY_TABLE_NAME
drop constraint <result from above>;
alter table MY_TABLE_NAME
add constraint fk_my_table_name_purpose foreign key (other_id)
references other_table(id) on delete cascade;
However, I try to avoid working directly with system tables and I'd like to know whether there is a better / more elegant way to alter my foreign key.
There's no better way, the system tables are the only way to figure out the constraint name.

SQL query error - can't see why?

I'm currently reading through this Yii application eBook: http://www.packtpub.com/agile-web-application-development-yii11-and-php5/book - and I'm having a problem inputting the tutorials DDL / SQL statements into PHPMyAdmin without it throwing up errors.
Would someone be kind enough to shed some light on why the following syntax is invalid? It might be something simple but I can't see it:
SQL statement:
ALTER TABLE tbl_issue
ADD CONSTRAINT FK_issue_project FOREIGN KEY (`project_id`)
REFERENCES tbl_project(`id`) ON DELETE CASCADE ON UPDATE RESTRICT;
ALTER TABLE tbl_issue
ADD CONSTRAINT `FK_issue_owner` FOREIGN KEY (`owner_id`)
REFERENCES tbl_user(`id`) ON DELETE CASCADE ON UPDATE RESTRICT;
ALTER TABLE tbl_issue
ADD CONSTRAINT `FK_issue_requester` FOREIGN KEY (`requester_id`)
REFERENCES tbl_user(`id`) ON DELETE CASCADE ON UPDATE RESTRICT;
ALTER TABLE tbl_project_user_assignment
ADD CONSTRAINT `FK_project_user` FOREIGN KEY (`project_id`)
REFERENCES tbl_project(`id`) ON DELETE CASCADE ON UPDATE RESTRICT;
ALTER TABLE tbl_project_user_assignment
ADD CONSTRAINT `FK_user_project` FOREIGN KEY (`user_id`)
REFERENCES tbl_user(`id`) ON DELETE CASCADE ON UPDATE RESTRICT;
INSERT INTO tbl_user (`email`, `username`, `password`)
VALUES
(`test1#notanaddress.com`,`Test_User_One`, MD5(`test1`)),
(`test2#notanaddress.com`,`Test_User_Two`, MD5(`test2`));
Error Message
Error
SQL query:
ALTER TABLE tbl_issue
ADD CONSTRAINT FK_issue_project FOREIGN KEY ( `project_id` )
REFERENCES tbl_project( `id` ) ON DELETE CASCADE ON UPDATE RESTRICT ;
MySQL said:
#1005 - Can't create table 'trackstar_test.#sql-c78_127' (errno: 121) (<a
href="server_engines.php?engine=InnoDB&page=Status&
token=252c0553975923580ca430b6e98c4243">Details...</a>)
Note:
All the tables in the database are set to innodb as their storage engine.
I've tried using different foreign key names for each FK, still get the same error.
Update:
After finding no solution to the problem, I deleted by DB, uninstalled Xampp and then redid everything again. Seems to work now. Sorry to not be able to tell future readers exactly what the cause was, but it was most probably to do with my Database config or the information I added to it.
Actual Problem is :
AS you are Following the book, there are a few insert/ update statements are executed on
tbl_proect,
tbl_issue
than you are trying to add Foreign Key Constraint. that checks the table data before applying. So, Here is the actual mistake, may be your tables contain a few records that violate the foreign key constraints. hence phpmyadmin doesnot allow you to alter table and generates error message.
Solution :
TRUNCATE TABLE `tbl_project`
TRUNCATE TABLE `tbl_issue`
Do Only one thing, clear all the tables . Empty tables. . And here's your problm resolved now phpmyadmin allows you to run commands.

What can I do about a SQL Server ghost FK constraint?

I'm having some trouble with a SQL Server 2005 database that seems like it's keeping a ghost constraint around. I've got a script that drops the constraint in question, does some work, and then re-adds the same constraint. Normally, it works fine. Now, however, it can't re-add the constraint because the database says that it already exists, even though the drop worked fine!
Here are the queries I'm working with:
alter table individual drop constraint INDIVIDUAL_EMP_FK
ALTER TABLE INDIVIDUAL
ADD CONSTRAINT INDIVIDUAL_EMP_FK
FOREIGN KEY (EMPLOYEE_ID)
REFERENCES EMPLOYEE
After the constraint is dropped, I've made sure that the object really is gone by using the following queries:
select object_id('INDIVIDUAL_EMP_FK')
select * from sys.foreign_keys where name like 'individual%'
Both return no results (or null), but when I try to add the query again, I get:
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "INDIVIDUAL_EMP_FK".
Trying to drop it gets me a message that it doesn't exist. Any ideas?
It means the data is wrong on creation of the FK
That is, you have "EMPLOYEE_ID" values in the INDIVIDUAL child table that don not exist in the parent EMPLOYEE table.
You could use ALTER TABLE ...WITH NOCHECK ADD CONSTRAINT... but then the FK is no use