Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete rows from multiple tables using a single query (SQL Express 2005) with a WHERE condition

This is the query I'm using:

 DELETE TB1.*, TB2.*    FROM TB1         INNER JOIN TB2 ON TB1.PersonID = TB2.PersonID    WHERE (TB1.PersonID)='2' 

It's working fine in MS Access but getting error (Incorrect syntax near ','.) in SQL Server Express 2005.

How to solve it? Please help.

like image 472
Jobi Avatar asked Nov 11 '09 11:11

Jobi


People also ask

Can we use WHERE clause with delete in SQL?

DELETE Syntax Notice the WHERE clause in the DELETE statement. The WHERE clause specifies which record(s) should be deleted. If you omit the WHERE clause, all records in the table will be deleted!

How do I delete a row from multiple tables in SQL?

Another way to delete multiple rows is to use the IN operator. DELETE FROM table_name WHERE column_name IN (value 1, value 2, value 3, etc...); If you want to delete all records from the table then you can use this syntax.

Can delete have WHERE clause?

You can use the WHERE clause with a DELETE query to delete the selected rows, otherwise all the records would be deleted.

How do you delete data from 3 tables in SQL?

If it works if all tables have records, try using LEFT JOIN instread of INNER JOIN. Also, You had some mess with Your joins ON conditions. Try it like this: delete relativedata, crawls, stored from relativedata LEFT join crawls on relativedata.


2 Answers

You cannot DELETE from multiple tables with a single expression in SQL 2005 - or any other standard SQL for that matter. Access is the exception here.

The best method to get this effect is to specify FOREIGN KEYS between the table with an ON DELETE trigger.

like image 82
Matijs Avatar answered Sep 22 '22 00:09

Matijs


Why you don't use a DELETE CASCADE FK ?

like image 24
Cesar Avatar answered Sep 22 '22 00:09

Cesar