1

I want to delete rows from two tables using single delete query for .net application.

CREATE TABLE Table1 (User_Id, Name, Address, Group);
CREATE TABLE Table2 (User_Id, Role, Application);

INSERT INTO Table1 VALUES ('Mike', 'Michael', 'NJ', 'Dev');
INSERT INTO Table1 VALUES ('Cla', 'Clark', 'Tampa', 'Supp');
INSERT INTO Table1 VALUES ('Ton', 'Tony', 'Tulsa', 'Tes');

INSERT INTO Table2 VALUES ('Ton', 'AM', 'Science');
INSERT INTO Table2 VALUES ('Cla', 'SM', 'Magazine');
INSERT INTO Table2 VALUES ('Mike','M', 'Sports');

DELETE Table1, Table2
FROM   Table1
JOIN   Table2 ON (Table2.User_Id = Table1.User_Id)
WHERE  Table1.User_Id = '';

Pls advice whether it is a good practice or is it better to go for SP?

3
  • stackoverflow.com/questions/11825648/… Please see above post, it will answer your query. Commented Dec 6, 2013 at 6:22
  • The link goes to a question tagged mysql. Does this work on SQL Server too? Commented Dec 6, 2013 at 6:26
  • Delete T1, T2 from Table1 T1 inner join Table 2 T2 ON T1.User_Id = T2.User_Id where T1.User_Id = //what should I put here since I am gonna use this for asp.net application. Certainly I can put values if I am gonna run it from SQL Server Commented Dec 6, 2013 at 6:29

2 Answers 2

2

this is only possible if you have a foreign key constraint between your tables and activate the "cascade delete" option on the constraint.

if you don't want a constraint (although I think it would be a good idea anyway) you could use a trigger to delete corresponding records in child tables

Sign up to request clarification or add additional context in comments.

1 Comment

+1 good answer... if you don't want to / or can't change the data structure or add a trigger you can always do the two delete statements in a transaction.
0

It doesn't possible directly. Of course we can. Lets do it another way

  1. Create ForeignKey with cascade delete enabled option
  2. Creating delete trigger on Table1

But in the case of performance i cant prefer u trigger. So enabling cascading Delete should be good.

ALTER TABLE Table2
ADD CONSTRAINT fk_Table1_User_ID
FOREIGN KEY (User_ID)
REFERENCES  Table1(User_ID)
ON DELETE CASCADE;

Cheers, Sarath

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.