6

I am trying to join 2 tables together and do a delete on it.

DELETE TableA 
FROM TableA a
INNER JOIN
TableB b on b.Id = a.Id
where title like 'test' 

The above is what I come up with however I keep getting

The DELETE statement conflicted with the REFERENCE constraint

I thought if I merge the 2 tables together then I will delete both at the same time and no constraints would be conflicted.

Am I missing something in my query?

2
  • Only one table is subject to delete (TableA here). This syntax is just for filtering the rows to delete. Commented Aug 8, 2012 at 17:15
  • Do you have your constraints to CASCADE DELETE? If you can add that, then it would help with these messages. Commented Aug 8, 2012 at 17:21

3 Answers 3

12

try this:

DELETE TableA 
FROM TableA 
INNER JOIN
TableB b on b.Id = TableA.Id
where TableA.title like 'test'
Sign up to request clarification or add additional context in comments.

Comments

6

First try to delete TableB with that title condition Then delete those records in TableA

DELETE FROM TableB
WHERE Id IN 
( SELECT Id FROM TableA WHERE title = 'test')

DELETE FROM TableA
WHERE title = 'test'

Referential Constraints blocks you from deleting rows in TableA when you still have reference in TableB

3 Comments

Sorry. I probably should have done a.Title = 'test'. TableB has no title column. TableB is a mapping table so it just contains data to map a few tables together.
in my query i am looking for title column in TableA only.
Ah I see. Still getting the foreign key constraint that is between those 2 tables. I see TableB has another foreign key but it is not complaining about that one.
0

I would delete one after the other with cascade constraint.

1 Comment

I was thinking of a cascade but I think I have to alter the table then and I don't want to touch the table design. If it is possible to set it on the fly then I would do it.

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.