如何用一条语句同时删除2张表的数据

来源:百度知道 编辑:UC知道 时间:2024/06/14 20:00:00
delete from table1,table2 where a=1
结果报错
请教高手

这肯定是错的了...

对于实现你的问题我想到了几个
1.可以利用表中的约束,也就是外键。在建立外键时建立一个数据操作同步。
例子:
Constraint FK_tbl1_tbl2 table1(列名) References table2(列名) on update cascade on delete cascade

其中on update cascade是在你对伊个表的相关列进行更新时,2个表同时都会更新。
而DELETE,则是删除,和更新同理。

2.可以利用触发器
用DELETE触发器
具体的写法希望WHITE_WIN大哥能说说,呵呵,我还没学到

3.也就是你写2条语句吧...呵呵

delete from table1,table2 where 1=1

楼主为什么要用一条啊?是为了实现要么同时删除,要么都不删除么?如果是的话,可以这样写
if exists (select * from table1 where a='1') and exists (select * from table2 where a='1')
begin
begin transaction
delete from table1
if @@error<>0
begin
rollback transaction
end
delete from table2
if @@error<>0
begin
rollback transaction
end
commit transaction
end

delete from table1;delete from table2 ;

delete from table1 where a=1
delete from table2 where a=1

只能分开写,想偷下懒是不行的哦

要想用 一条语句学 就用触发器 做<