It's possible to delete using join statements to qualify the set to be deleted, such as the following:
DELETE J FROM Users U inner join LinkingTable J on U.id = J.U_id inner join Groups G on J.G_id = G.id WHERE G.Name = 'Whatever' and U.Name not in ('Exclude list')
However I'm interested in deleting both sides of the join criteria -- both the LinkingTable
record and the User record on which it depends. I can't turn cascades on because my solution is Entity Framework code first and the bidirectional relationships make for multiple cascade paths.
Ideally, I'd like something like:
DELETE J, U FROM Users U inner join LinkingTable J on U.id = J.U_id ...
Syntactically this doesn't work out, but I'm curious if something like this is possible?
The syntax also supports deleting rows from multiple tables at once. To delete rows from both tables where there are matching id values, name them both after the DELETE keyword: DELETE t1, t2 FROM t1 INNER JOIN t2 ON t1.id = t2.id; What if you want to delete nonmatching rows?
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 .
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.
Nope, you'd need to run multiple statements.
Because you need to delete from two tables, consider creating a temp table of the matching ids:
SELECT U.Id INTO #RecordsToDelete FROM Users U JOIN LinkingTable J ON U.Id = J.U_Id ...
And then delete from each of the tables:
DELETE FROM Users WHERE Id IN (SELECT Id FROM #RecordsToDelete) DELETE FROM LinkingTable WHERE Id IN (SELECT Id FROM #RecordsToDelete)
The way you say is Possible in MY SQL
but not for SQL SERVER
You can use of the "deleted" pseudo table for deleting the values from Two Tables at a time like,
begin transaction; declare @deletedIds table ( samcol1 varchar(25) ); delete #temp1 output deleted.samcol1 into @deletedIds from #temp1 t1 join #temp2 t2 on t2.samcol1 = t1.samcol1 delete #temp2 from #temp2 t2 join @deletedIds d on d.samcol1 = t2.samcol1; commit transaction;
For brief Explanation you can take a look at this Link
and to Know the Use of Deleted Table you can follow this Using the inserted and deleted Tables
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With