我有一个Audit表来跟踪插入/更新操作。 我的问题是在更新时有2个案例。 1)定期更新 2)将名为Isdeleted的字段从false更新为true。
我试图将两个案例分开,但我遗漏了一些东西,我不熟悉触发器。
DECLARE @Action AS CHAR(1)
DECLARE @Count AS INT
SET @Action = 'I'
SELECT @Count = COUNT(*) FROM DELETED
if @Count > 0
BEGIN
SET @Action = 'D'
SELECT @Count = COUNT(*) FROM INSERTED WHERE INSERTED.IsDeleted = 0
IF @Count > 0
SET @Action = 'U'
END
我想要做的是当更改的唯一值是IsDeleted(从false到true)时,转到Action ='D'。 当任何其他值发生变化时,'U'。
答案 0 :(得分:1)
根据您创建触发器的方式,您可以修改它以使用UPDATE()
来简化设置@Action
值的逻辑。
例如:
CREATE TRIGGER myTrigger ON myTable AFTER UPDATE, DELETE
BEGIN
DECLARE @Action AS CHAR(1)
IF UPDATE(isDeleted)
SET @Action = 'U'
END
当SET
列发生更改时,每次都会触发@Action
isDeleted
的值,我认为这是您正在寻找的内容。
我不确定你将要做什么,但它会做你需要的。
答案 1 :(得分:0)
此选择将返回IsDeleted列从0更新为1的行数:
select count(*)
from inserted inner join deleted on <fk_column(s)>
where deleted.IsDeleted = 0
and inserted.IsDeleted = 1
但是,由于触发器每个语句(而不是每行)都有效,因此可能会出现删除某些行而某些行刚刚更新的情况,因此保持每行的操作可能会比那更棘手。
答案 2 :(得分:0)
试试这个:
DECLARE @Action AS CHAR(1)
DECLARE @Count AS INT
IF NOT EXISTS(SELECT 1 FROM Deleted)
BEGIN
SELECT
@Action = 'I'
END
ELSE
BEGIN
SELECT
@Count = COUNT(1)
FROM Inserted Ins
INNER JOIN Deleted Del
ON Ins.SeqNo = Del.SeqNo
WHERE ISNULL(Ins.IsDeleted,0) <> ISNULL(Del.IsDeleted,0)
AND Ins.Column1 = Del.Column1
AND Ins.Column2 = Del.Column2
AND Ins.ColumnN = Del.ColumnN
SELECT
@Action = CASE WHEN ISNULL(@Count,0)>0
THEN 'D'
ELSE 'U' END
END
SELECT
[ActionCode] = @Action