一个简单的触发器的写法 在线等
一个表a有Id,OrderName 和 OrderValue,..列
我想写一个触发器更新这OrderValue列
当OrderName= 'AA ' OrderValue=1
当OrderName= 'A ' OrderValue=2
只有当更新OrderName时更新OrderValue的值。
我写了一个触发器
create TRIGGER tr_test ON a
FOR UPDATE ,insert
AS
BEGIN
DECLARE @OrderName nvarchar(10)
DECLARE @ID int
if update(OrderName)
begin
SELECT @OrderName=OrderName ,@ID= ID FROM a
IF @OrderName = 'AA '
UPDATE a SET OrderValue=1 WHERE ID = @ID
ELSE IF @OrderName = 'A '
UPDATE a SET OrderValue=2 WHERE ID = @ID
end
END
但我在批更新的时候,只是更新了最后一条。该怎么改这个触发器
------解决方案--------------------create TRIGGER tr_test ON a
FOR UPDATE ,insert
AS
BEGIN
DECLARE @OrderName nvarchar(10)
DECLARE @ID int
if update(OrderName)
begin
UPDATE A SET
OrderValue = CASE WHEN I.OrderName = 'AA ' then 1 ELSE 2 END
FROM A, inserted I
WHERE A.ID = i.id
and i.ordername IN( 'aa ', 'a ')
end
END
------解决方案--------------------我的写错了,不过上面的多少有点小问题
create TRIGGER tr_test ON a
FOR UPDATE ,insert
AS
BEGIN
if update(OrderName)
update a
set OrderValue=case i.OrderName when 'AA ' then 1
when 'A ' then 2
else a.OrderValue
end
from a,inserted i
where a.id=i.id
END