2012-09-29 86 views
1

我正在處理sql中的觸發器。我試圖做一個更新觸發器,但是我希望它只在滿足某些條件時才起作用。SQL更新觸發條件

例如讓我說我有一個表X和兩列A,B。 我希望只有在A小於B時才能更新A或B,以便將新值更新。

所以我做一個觸發器這樣

create trigger utrigger 
on X 
for update as 
if (update(A) OR update(B)) 
begin 


if (A>B) 
RAISERROR (N' Incorrect %s %d.', -- Message text. 
     10, -- Severity, 
     1, -- State, 
     N'number', -- First argument. 
     5); -- Second argument. 

不過,我覺得我做錯了。這有什麼不對?

+0

此條件是否也適用於插入?如果這是應該應用於所有行的,那麼'CHECK(B <= A)'上的檢查約束將更有效。 –

回答

4

您需要使用INSERTED虛擬表。

create trigger utrigger 
on X 
for update as 
if (update(A) OR update(B)) 
begin 
if exists (SELECT * -- this subquery breaches the condition 
      FROM INSERTED 
      WHERE A>=B) -- might need some isnull if nulls are not allowed 
RAISERROR (N' Incorrect %s %d.', -- Message text. 
     10, -- Severity, 
     1, -- State, 
     N'number', -- First argument. 
     5); -- Second argument. 
end 
+0

是的,它的工作。謝謝 – Maverick