我需要创建一个SQL Server触发器来阻止对表Service
的更新和删除。
此操作只应针对Service
列State
的示例数据已完成的Service
。
它应允许更新和删除State
列Service
的样本数据为“有效”。
这是我尝试过的,我在执行else操作时遇到了问题(即允许更新State
列CREATE 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
答案 0 :(得分:1)
因此,如果我理解正确,如果UPDATE
列的值为DELETE
,则应允许State
或Active
,但在任何其他情况下都会停止? ?
然后我就这样做了:
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
) - 通过回滚当前活动的事务,触发器无声地失败