0

I have 2 related tables called tblResponse and tblUser, I want to delete records from tblUser which have a value of inactive in the status column.

In the tblResponse table, I also want to delete all these records whose UserId from tblUser have been deleted.

Each UserId potentially has multiple responses in tblResponse table, it needs to delete all of them.

This jobs needs to run everyday.

 DELETE A
 FROM tblUser A
 INNER JOIN tblUser U ON UserId = EmployeeID
 WHERE UserStatus = 'Inactive'

In the above query UserId is from tblUser and EmployeeID is from tblResponse.

How can I delete the data from 2 tables ?

3
  • What's the question? Commented Apr 10, 2018 at 15:17
  • how can i delete the data from 2 tables Commented Apr 10, 2018 at 15:19
  • 2
    Set up a foreign key constraint (w/ cascading deletes) when creating the Response table. That's what they're for! Commented Apr 10, 2018 at 15:27

1 Answer 1

2

The usual way to handle this is to set up the tables with a foreign key constraint, where the ON DELETE is set to CASCADE:

CREATE TABLE Users 
(
    ID INT NOT NULL PRIMARY KEY CLUSTERED IDENTITY(1, 1),
    ... other fields
)

CREATE TABLE Responses 
(
    ID INT NOT NULL PRIMARY KEY CLUSTERED IDENTITY(1, 1),
    UserID INT NOT NULL REFERENCES dbo.Users (ID) 
        ON UPDATE CASCADE  -- when UserID updated, update this UserID also
        ON DELETE CASCADE, -- when User deleted, delete these rows also
    ... other fields
)

This is of course the preferred method because it instructs the database to maintain its own integrity without requiring the application layers to handle it.

Occasionally this cannot be done though, either due to pre-existing tables with bad data (where we should then consider cleaning the data then applying the constraint), or possible circular constraints, in which case you have to use two delete statements:

-- remove the associated responses first
DELETE r
FROM Users AS u
INNER JOIN Responses AS r ON u.ID = r.UserID
WHERE u.Active = 0;

-- then delete your users
DELETE FROM Users WHERE Active = 0;
Sign up to request clarification or add additional context in comments.

4 Comments

Transacting the multiple deletes might be to maintain data integrity.
will we face any issue in future if we go without using foreignkey constraint and delete using multiple deletes ?
Data integrity is the only real issue, but that can be a very big issue if left unchecked. FK constraints are typically much preferred, but a sound education on database design would arm you with the ability to best answer your question (e.g., hard for me to say for sure)
Thank you, in that case i feel it is best to create a foreign key constraint on the table..

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.