How to delete rows in associated SQL tables? - sql

I want to delete rows in GlassesColor table that associated with GlassesID in Glasses table.
I want to implement this in stored procedure.The stored procedure gets only one parameter from client side , a CollectionID.
Here are the following tables:
Here is example of tables content:
Any idea how can i implement this?
Thank you in advance!

Manually deleting would be something like this:
delete
from GlassesColor
where GlassesID in (select GlassesID from Glasses where CollectionID = 3)
However, unless this is a one time cleanup, you should start specifying foreign key cascading rules, like the other answers already suggested.

The easiest way is to define FOREIGN KEYS with CASCADE options for DELETE.
http://msdn.microsoft.com/en-us/library/aa933119%28v=sql.80%29.aspx
I see you already have Foreign Keys defined, so you just need to make sure they have CASCADE option for DELETE.

Without stored procedure, use Constrains -> http://www.mssqlcity.com/Articles/General/using_constraints.htm OnDelete Cascade, so when you delete row in Glasses, it will deleted in Glasses color also.

In your foreign key constraint for the GlassesColor join table, have on delete cascade. What that means is when the primary key referenced record is deleted, the corresponding foreign key reference row will also be deleted.
So your GlassesColor table definition would look like this:
create table GlassesColor
(
GlassesId int foreign key references Glasses(GlassesID) on delete cascade,
.....
)
go

I answered something similar for using the INFORMATION_SCHEMA in MSSQL
SQL Server: drop table cascade equivalent?

Here's the easiest way to do it in Microsoft SQL Server: when you create the foreign key constraint, add ON UPDATE CASCADE ON DELETE CASCADE to its definition. I'm assuming you want changes to GlassesID to also propogate. ;-) If not, then you don't need the "ON UPDATE CASCADE".
Example:
ALTER TABLE
[GlassesColor]
WITH CHECK ADD CONSTRAINT
[FK_GlassesColor_GlassesID]
FOREIGN KEY
([glassesID]) REFERENCES [Glasses] ([glassesID])
ON UPDATE CASCADE ON DELETE CASCADE

Related

Using Multiple FK & "ON DELETE SET NULL" in a single table

I have two tables, Entity and Arrest. The Entity table is where I store all my people. The arrest table is where I handle criminal arrests. In the arrest table there is multiple FK's to the Entity Table IE (Who was arrested, who did the arresting, and a couple more). If I delete the entity I want to null out all of the entity FK in the arrest table. However, I get error's when I add "On Delete set null" action to the my second FK.
Here is the FK code and the error I get.
ALTER TABLE[arrest].[Arrest] WITH CHECK ADD CONSTRAINT[FK_arrest_TreatedBy] FOREIGN KEY([TreatedBy])
REFERENCES[entity].[Entity]([ID])
ON DELETE SET NULL ON UPDATE NO ACTION
GO
ALTER TABLE[arrest].[Arrest] CHECK CONSTRAINT[FK_arrest_TreatedBy]
GO
ALTER TABLE[arrest].[Arrest] WITH CHECK ADD CONSTRAINT[FK_arrest_arrestee] FOREIGN KEY([Arrestee])
REFERENCES entity.entity([ID])
ON DELETE SET null ON UPDATE NO ACTION
GO
ALTER TABLE[arrest].[Arrest] CHECK CONSTRAINT[FK_arrest_arrestee]
GO
Introducing FOREIGN KEY constraint 'FK_arrest_arrestee' on table 'Arrest' may cause cycles or multiple cascade paths.Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
try to use CASCADE for DELETE ,
UPDATE CASCADE in SQL Server foreign key

Two FKs pointing to same parent column - ON UPDATE CASCADE - SQL Server

Here's the scenario.
- Parent Table: TEAMMEMBERS, with a primary key RecID
- Child Table: TEAMMEMBERTASKS
I have two columns in the TEAMMEMBERTASKS table, ReportedBy and AssignedTo.
Both of these columns use the RecID to store which team member reported a task and which team member the task is assigned to. The RecID could be the same for both columns, but that is not always the case.
I need to add in a FK for both child columns that check the relationship to the parent, and I would like to add ON UPDATE CASCADE to both of the foreign keys.
Whenever I try to do this, my second foreign key throws a 'may cause cycles or multiple cascade paths' error.
Here's my code:
ALTER TABLE [dbo].[TEAMMEMBERTASKS] WITH CHECK ADD CONSTRAINT
[FK_AssignedTo_TeamMemberRecID] FOREIGN KEY([AssignedTo])
REFERENCES [dbo].[TEAMMEMBERS] ([RecID])
GO
ALTER TABLE [dbo].[TEAMMEMBERTASKS] CHECK CONSTRAINT
[FK_AssignedTo_TeamMemberRecID]
GO
ALTER TABLE [dbo].[TEAMMEMBERTASKS] WITH CHECK ADD CONSTRAINT
[FK_ReportedBy_TeamMemberRecID] FOREIGN KEY([ReportedBy])
REFERENCES [dbo].[TEAMMEMBERS] ([RecID])
ON UPDATE CASCADE
GO
ALTER TABLE [dbo].[TEAMMEMBERTASKS] CHECK CONSTRAINT
[FK_ReportedBy_TeamMemberRecID]
GO
With the current code, will this cause the RecID to be updated in both child columns or will it cause the update command to be restricted?
Should I just go ahead and write up a trigger that deals with this instead?

How to delete records from parent table which is referenced by multiple child tables?

I have a table which is referenced by multiple tables (around 52) and further,few of the child tables have multiple foreign keys also that is referencing other tables too.
I want to delete a record from parent table, I am unable to do so, as I am getting error "The DELETE statement conflicted with the REFERENCE constraint "FK_xxx". The conflict occurred in database "MyDB", table "dbo.A", column 'x'."
I want a generalized T-SQL solution which is irrespective of tables and number of references.
You have to look at the "on delete" keyword which is a part of the foreign key constraint definition.
Basically you have 4 options:
NO ACTION (does nothing)
CASCADE (deletes the child aswell)
SET NULL (sets the reference field to null)
SET DEFAULT (sets the reference field to the default value)
An example would be:
CREATE TABLE parent (
id INT NOT NULL,
PRIMARY KEY (id)
) ENGINE=INNODB;
CREATE TABLE child (
id INT,
parent_id INT,
INDEX par_ind (parent_id),
FOREIGN KEY (parent_id)
REFERENCES parent(id)
ON DELETE CASCADE -- replace CASCADE with your choice
) ENGINE=INNODB;
(for this example and more details look here: http://dev.mysql.com/doc/refman/5.7/en/create-table-foreign-keys.html )
If you now want to modify your constraint, you first have to drop it, and create a new one like for example:
ALTER TABLE child
ADD CONSTRAINT fk_name
FOREIGN KEY (parent_id)
REFERENCES parent(id)
ON DELETE CASCADE; -- replace CASCADE with your choice
I hope this helped. Also to mention it, you should think about maybe not really deleting your parent, and instead creating another boolean column "deleted", which you fill with "yes" if someone clicks the delete. In the "Select"-query you filter then by that "deleted" column.
The advantage is, that you do not lose the history of this entry.
Your problem is this: A FK constraint is designed to prevent you from creating an orphaned child record in any of the 52 tables. I can provide you with the script you seek, but you must realise first that when you try to re-enable the FK constraints the constraints will fail to re-enable because of the orphaned data (which the FK constraints are designed to prevent). For your next step, will have to delete the orphaned data in each of the 52 tables first anyway. It is actually much easier just to redo the constraints with ON DELETE CASCADE, or drop the constraints and forget about referential integrity altogether. You can't have it both ways.

SQL delete query with foreign key constraint

I know that this question belongs to the very early stages of the database theory, but I have not encountered such a problem since several months. If someone has a database with some tables associated together as "chain" with foreign keys and they want to delete a record from a table which has some "dependent" tables, what obstacles arise? In particular, in a database with tables: Person, Profile, Preference, Filter exist the associations as Person.id is foreign key in Profile and Profile.id is foreign key in Preference and Filter.id is foreign key in Preference, so as that all the associationsenter code here are OneToMany. Is it possible to delete a Person with a simple query:
Delete from Person p where p.id= 34;
If no, how should look like the query in order to perform the delete successfully?
If the database in the application is managed by hibernate, what constraints (annotations) should I apply to the associated fields of each entity, so as to be able with the above simple query to perform the delete?
FOR SQL VERSION
Look at the Screenshot. you can use the Insert Update Specificaiton Rules. as it has Delete and Update Rules. you can set either of these values.
Foreign key constraints may be created by referencing a primary or unique key. Foreign key constraints ensure the relational integrity of data in associated tables. A foreign key value may be NULL and indicates a particular record has no parent record. But if a value exists, then it is bound to have an associated value in a parent table. When applying update or delete operations on parent tables there may be different requirements about the effect on associated values in child tables. There are four available options in SQL Server 2005 and 2008 as follows:
No Action
Cascade
SET NULL
SET Default
Use this article for Refrence.
http://www.mssqltips.com/sqlservertip/2365/sql-server-foreign-key-update-and-delete-rules/
ORACLE VERSION
you can use one of below.
alter table sample1
add foreign key (col1)
references
sample (col2)
on delete no action;
alter table sample1
add foreign key (col1)
references
sample (col2)
on delete restrict;
alter table sample1
add foreign key (col1)
references sample (col2)
on delete cascade;
for refrance.
http://docs.oracle.com/cd/B19306_01/server.102/b14200/clauses002.htm
answer is no if there is foreign key constraint then you have to delete leaf node table data first
that is first delete from Preference table
then from Profile and Filter Table
then delete record from Person table
This is the generic concept that you apply anywhere

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.