我在T-SQL中相当新,但我有一个关于触发器的问题。我编写了一个触发器,用于我的存储过程中插入和更新数据。
现在,当表[dbo].[users]
我不知道如何修改此触发器,以便在将数据插入[dbo].[users]
表时激活触发器(现在可以正常工作),但如何在同一触发器上实现更新方案,如果只是[dbo].[users]
表中的特定行已更新,只有触发器才会被激活。
例如
如果插入了新用户且所有行都插入此表中 - 激活触发器
如果更新了旧触发器,但只更新了此表中的特定字段(working_state是列的名称),则只应激活触发器。
源代码我所拥有的内容如下所示:
ALTER TRIGGER [dbo].[t_temp_triger_name]
ON [dbo].[users]
AFTER INSERT, UPDATE, DELETE
AS
BEGIN
DECLARE @working_state char(1),
@user_code char(11)
DECLARE zm CURSOR FOR
SELECT
working_state,
user_code
FROM
inserted
-- Added update statement that activates the trigger only when a specific -
-- column update is executed
UPDATE [dbo].[users]
SET working_state = 1
FROM [dbo].[users] U
INNER JOIN DELETED D ON U.user_code= D.user_code
WHERE U.working_state<> D.working_state
OPEN zm
FETCH NEXT FROM zm INTO @working_state, @user_code
WHILE @@FETCH_STATUS = 0
BEGIN
EXEC [FNF].[dbo].[NamedProcedure]
@working_state, @user_code
FETCH NEXT FROM zm INTO @working_state, @user_code
END
CLOSE zm
DEALLOCATE zm
END
答案 0 :(得分:0)
我想出了一个解决方案
在声明
之后将其添加到我的代码中一切正常。
IF EXISTS (SELECT 1 FROM deleted)
BEGIN
DECLARE zm CURSOR FOR
SELECT
u.working_state,
u.user_code
FROM
inserted U
LEFT JOIN DELETED D ON U.user_code= D.user_code
WHERE U.working_state<> D.working_state
END
ELSE
BEGIN
DECLARE zm CURSOR FOR
SELECT
working_state,
user_code
FROM
inserted
END