日期:2014-05-19  浏览次数:20664 次

请教关于sqlserver2000触发器delete的问题
表A:
字段:id,...
表B:
字段:id,A_id,...
其中表B.A_id与表A.id相关联
在表A建立一个触发器,希望在删除表A的数据是同时能将表B的相关数据删除:
create   TRIGGER   trgA_Delete
ON   A
FOR   Delete   /*   INSERT,   UPDATE,   DELETE   */
AS                   /*   IF   UPDATE   (column_name)   ...*/
Declare   @A_id   int
Set   @A_id=(select   id   from   deleted)
begin
Delete   from   B   where   A_id=@A_id
end
当一条一条的删除表A数据的时候,这个触发器正常
但当我想给表A作初始化,需要清空表A时问题就出现了
子查询返回的值多于一个。当子查询跟随在   =、!=、 <、 <=、> 、> =   之后,或子查询用作表达式时,这种情况是不允许的。
语句已终止。
初学者,大家帮忙


------解决方案--------------------
create TRIGGER trgA_Delete
ON A
FOR Delete /* INSERT, UPDATE, DELETE */
AS /* IF UPDATE (column_name) ...*/

Delete x from B as x inner Join deleted as y on x.A_id=y.id
go
------解决方案--------------------
create TRIGGER trgA_Delete
ON A
FOR Delete /* INSERT, UPDATE, DELETE */
AS /* IF UPDATE (column_name) ...*/
begin
Delete from B where A_id in (select id from deleted)
end

------解决方案--------------------
create TRIGGER trgA_Delete
ON A
FOR Delete /* INSERT, UPDATE, DELETE */
AS /* IF UPDATE (column_name) ...*/
/*
Declare @A_id int
Set @A_id=(select id from deleted)
begin
*/
Delete from B where A_id in (select id from deleted)
--或
--delete from b where exists(select 1 from deleted d where d.id=b.A_id)
--end
------解决方案--------------------
deleted临时表中有多条时要用in.
如果只有一条可以这样
create TRIGGER trgA_Delete
ON A
FOR Delete /* INSERT, UPDATE, DELETE */
AS /* IF UPDATE (column_name) ...*/
/*
Declare @A_id int
Set @A_id=(select id from deleted)
begin
*/
Delete from B where A_id = (select top 1 id from deleted)
--end


------解决方案--------------------
create TRIGGER trgA_Delete
ON A
FOR Delete /* INSERT, UPDATE, DELETE */
AS /* IF UPDATE (column_name) ...*/

begin
delete from b where exists(select 1 from deleted d where d.id=b.A_id)
end