[英]How to Delete a row from more than one table with one sql query where email id is same
Table1
- name
- phone
- age
- email
Table2
- name
- phone
- age
- email
I want to delete those data which has the same email in both tables.我想删除两个表中具有相同 email 的那些数据。
SQL Server does not support multi-table deletes, so you need two delete
statements (as commented by Larnu). SQL 服务器不支持多表删除,所以需要两条
delete
语句(Larnu评论)。
But it is still a bit tricky since you need to keep track of the emails that were deleted by the first statement so you can use them in the second one.但这仍然有点棘手,因为您需要跟踪第一个语句删除的电子邮件,以便您可以在第二个语句中使用它们。 I would recommend a table variable, that you can feed with a
output
clause:我会推荐一个表变量,你可以用
output
子句来提供:
begin transaction;
declare @deleted_emails table (email nvarchar(100));
-- or whatever datatype/length you use
delete from table1
output deleted.email into @deleted_emails
where exists (select 1 from table2 t2 where t2.email = table1.email)
delete from table2
where exists (select 1 from @deleted_emails d where d.email = table2.email);
commit transaction;
Wrapping the code in a transaction
makes it atomic (that is, the changes done by both statements are commited or rolled back together).将代码包装在
transaction
中使其具有原子性(即,两个语句所做的更改一起提交或回滚)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.