读书人

求一触发器实现在insertupdate时对

发布时间: 2012-03-20 14:01:11 作者: rapoo

求一触发器,实现在insert,update时对表的操作。
有两张表temp_1,temp_2

SQL code
   CREATE TABLE temp_2(c1 INT,c2 INT )    CREATE TABLE temp_2(c1 INT,c2 INT )   INSERT INTO temp_2(c1,c2) VALUES(1,1),(2,2),(3,3)    INSERT INTO temp_1(c1,c2) VALUES(1,1),(1,2),(1,3)   

现在要实现:建立一个触发器在temp_1表上,假如向表temp_1插入(1,5),那么把 temp_1表中c1=1 并且c2的最大值取出来,更新到 temp_2中c1=1 的c2列中,我写了个触发器如下,但是实现不了取最大值功能,各位高手帮忙补充下,谢谢!
SQL code
    ALTER TRIGGER tr_1    ON temp_1     after INSERT,update    as     begin     UPDATE a SET a.c2 = b.c2     FROM temp_2 a,INSERTED b     WHERE a.c1=b.c1 AND EXISTS(SELECT MAX(c2) FROM temp_1 WHERE c1 =INSERTED.c1 GROUP BY c1 )    END   

其中
SQL code
AND EXISTS(SELECT MAX(c2) FROM temp_1 WHERE c1 =INSERTED.c1 GROUP BY c1 )
明显错误


[解决办法]
探讨
create TRIGGER tr_1 ON temp_1 for INSERT,update
as
begin
update temp_2 set c2 = (select max(c2) from temp_1 where c1 = (select c1 from inserted)) where c1 = (select c1 from inserted)
end

读书人网 >SQL Server

热点推荐