SQL Server中的IF语句触发器

时间:2016-07-10 07:15:10

标签: if-statement triggers sql-server-2014

我需要创建一个SQL Server触发器来阻止对表Service的更新和删除。

此操作只应针对ServiceState的示例数据已完成的Service

它应允许更新和删除StateService的样本数据为“有效”。

这是我尝试过的,我在执行else操作时遇到了问题(即允许更新StateCREATE TRIGGER [Triggername] ON dbo.Service FOR INSERT, UPDATE, DELETE AS DECLARE @para varchar(10), @results varchar(50) SELECT @para = Status FROM Service IF (@para = 'completed') BEGIN SET @results = 'An invoiced service cannot be updated or deleted!'; SELECT @results; END BEGIN RAISERROR ('An invoiced service cannot be updated or deleted', 16, 1) ROLLBACK TRANSACTION RETURN END 样本数据为“活动”。

match

1 个答案:

答案 0 :(得分:1)

因此,如果我理解正确,如果UPDATE列的值为DELETE,则应允许StateActive,但在任何其他情况下都会停止? ?

然后我就这样做了:

CREATE TRIGGER [Triggername]
ON dbo.Service
FOR UPDATE, DELETE
AS
BEGIN
   -- if any row exists in the "Deleted" pseudo table of rows that WERE 
   -- in fact updated or deleted, that has a state that is *not* "Active"
   -- then abort the operation
   IF EXISTS (SELECT * FROM Deleted WHERE State <> 'Active')
        ROLLBACK TRANSACTION

   -- otherwise let the operation finish 
END

作为备注:无法轻松地从触发器返回消息(使用SELECT @Results) - 通过回滚当前活动的事务,触发器无声地失败