Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inner Join Delete in SQL Server 2008?

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?

like image 877
chobo2 Avatar asked Aug 08 '12 17:08

chobo2


People also ask

Can you delete with an inner join?

Delete with inner join is used to delete all the records from the first table and all the matching records from the second table.

Can we use inner join in delete statement in SQL Server?

A DELETE statement can include JOIN operations.

How use Delete command inner join SQL Server?

Just add the name of the table between DELETE and FROM from where you want to delete records, because we have to specify the table to delete. Also remove the ORDER BY clause because there is nothing to order while deleting records. This one works on SQL Server if you only intend to delete from the first table.


2 Answers

try this:

DELETE TableA 
FROM TableA 
INNER JOIN
TableB b on b.Id = TableA.Id
where TableA.title like 'test'
like image 105
jyoti Avatar answered Nov 15 '22 07:11

jyoti


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

like image 44
sundar Avatar answered Nov 15 '22 05:11

sundar