sql触发器IF语句

时间:2013-12-12 14:17:08

标签: sql sql-server-2008 triggers

我在检测到特定列的值时创建了以下触发器:

ALTER TRIGGER [dbo].[trCompletedDate] ON [dbo].[Record]
FOR UPDATE AS BEGIN
IF(UPDATE(Completed))

UPDATE Record SET Completed_Date=DATEADD(hh, 7, GETDATE())
FROM Record 
INNER JOIN Inserted ON Record.[ID]= Inserted.[ID]
WHERE Record.Completed = 1
END

哪个工作正常,但我想在Record.Completed = 0时添加一个IF语句将Completed_Date的值更改为另一个值。

我只是不确定语法如何。

4 个答案:

答案 0 :(得分:3)

UPDATE Record SET Completed_Date = 
CASE WHEN Record.Completed = 1 THEN
   DATEADD(hh, 7, GETDATE())
ELSE
   --Somethin else
END
FROM Record 
INNER JOIN Inserted ON Record.[ID]= Inserted.[ID]

答案 1 :(得分:0)

您可以使用CASE声明:

UPDATE Record 
SET Completed_Date = 
    CASE Record.Completed WHEN 1 THEN DATEADD(hh, 7, GETDATE())
                          WHEN 0 THEN SOMETHINGELSE END
FROM Record 
INNER JOIN Inserted ON Record.[ID]= Inserted.[ID]
WHERE Record.Completed IN (0,1);

答案 2 :(得分:0)

我相信它是:

ALTER TRIGGER [dbo].[trCompletedDate] ON [dbo].[Record]
FOR UPDATE AS BEGIN
IF(UPDATE(Completed))

UPDATE Record SET 
    Completed_Date=if Record.Completed=0 then <othervalue> 
                   else DATEADD(hh, 7, GETDATE()) endif
FROM Record 
INNER JOIN Inserted ON Record.[ID]= Inserted.[ID]
WHERE Record.Completed = 1
END

答案 3 :(得分:0)

你走了:

ALTER TRIGGER [dbo].[trCompletedDate] ON [dbo].[Record]
FOR UPDATE AS BEGIN
IF(UPDATE(Completed))

UPDATE Record SET Completed_Date=
    CASE Record.Completed
        WHEN 1 THEN DATEADD(hh, 7, GETDATE())
        WHEN 0 THEN GETDATE()
    END
FROM Record 
INNER JOIN Inserted ON Record.[ID]= Inserted.[ID]
END