SQL query error - can't see why? - sql

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.

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)

How to put Cascade on Delete once the Fk constraint has already been defined [duplicate]

I have a table representing users. When a user is deleted I get:
DELETE statement conflicted with the REFERENCE constraint
Apparently, CASCADE DELETE is not as easy as I imagined in SQL Server, and the option needs to be added to the table.
The problem is: I cannot figure out how to add the CASCADE DELETE option.
I'm using: SQL Server 2008. Any ideas how to do this?
Read this Microsoft article first. Read Me. I use the GUI during design so here is a picture of how it is selected in SSMS.
The syntax added to the foreign key is " ON DELETE CASCADE "
Here's the way I would add the "cascading delete" feature to an existing foreign key in SQL Server Management Studio.
First, find your foreign key, and open it's "DROP and CREATE To" in a new Query window.
Then, just add "ON DELETE CASCADE" to the "ADD CONSTRAINT" command:
Then just hit hit the "Execute" button to run the query.
Job done !
Google ALTER TABLE DROP CONSTRAINT, then ALTER TABLE ADD CONSTRAINT:
ALTER TABLE
Here's a quick example:
CREATE TABLE A
(
ID INTEGER NOT NULL UNIQUE
);
CREATE TABLE B
(
ID INTEGER NOT NULL UNIQUE
CONSTRAINT fk__B__A
REFERENCES A (ID)
);
-- Oops! Forgot the CASCADE referential actions.
-- DROP the constraint then recreate it:
ALTER TABLE B DROP
CONSTRAINT fk__B__A;
ALTER TABLE B ADD
CONSTRAINT fk__B__A
FOREIGN KEY (ID)
REFERENCES A (ID)
ON DELETE CASCADE
ON UPDATE CASCADE;

Unable to add foreign key constraint due to obscure conflict

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.

How do I edit a table in order to enable CASCADE DELETE?

I have a table representing users. When a user is deleted I get:
DELETE statement conflicted with the REFERENCE constraint
Apparently, CASCADE DELETE is not as easy as I imagined in SQL Server, and the option needs to be added to the table.
The problem is: I cannot figure out how to add the CASCADE DELETE option.
I'm using: SQL Server 2008. Any ideas how to do this?
Read this Microsoft article first. Read Me. I use the GUI during design so here is a picture of how it is selected in SSMS.
The syntax added to the foreign key is " ON DELETE CASCADE "
Here's the way I would add the "cascading delete" feature to an existing foreign key in SQL Server Management Studio.
First, find your foreign key, and open it's "DROP and CREATE To" in a new Query window.
Then, just add "ON DELETE CASCADE" to the "ADD CONSTRAINT" command:
Then just hit hit the "Execute" button to run the query.
Job done !
Google ALTER TABLE DROP CONSTRAINT, then ALTER TABLE ADD CONSTRAINT:
ALTER TABLE
Here's a quick example:
CREATE TABLE A
(
ID INTEGER NOT NULL UNIQUE
);
CREATE TABLE B
(
ID INTEGER NOT NULL UNIQUE
CONSTRAINT fk__B__A
REFERENCES A (ID)
);
-- Oops! Forgot the CASCADE referential actions.
-- DROP the constraint then recreate it:
ALTER TABLE B DROP
CONSTRAINT fk__B__A;
ALTER TABLE B ADD
CONSTRAINT fk__B__A
FOREIGN KEY (ID)
REFERENCES A (ID)
ON DELETE CASCADE
ON UPDATE CASCADE;

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