我有一个触发表更新的SQL触发器。更新表时,它会修改另一个表中的某些字段。
它似乎工作但我不确定我设置状态的方式是否正确(如果插入包含多行)。我测试了它并得到了正确的答案(但我仍然怀疑这不是正确/最好的方式)。
CREATE TRIGGER [dbo].[myTrigger]
ON [dbo].[myTable]
AFTER UPDATE
AS
BEGIN
SET NOCOUNT ON
declare @OldStatus int
declare @NewStatus int
select @OldStatus = [currentStatus] FROM INSERTED
if @OldStatus = 1 or @OldStatus = 3 or @OldStatus = 5
begin
set @NewStatus = 1
end
if @OldStatus = 8 or @OldStatus = 9
begin
set @NewStatus = 8
end
if @OldStatus = 11 or @OldStatus = 12 or @OldStatus = 13
begin
set @NewStatus = 11
end
UPDATE myNewTable SET [LastModifiedDate] = GETDATE(),
[Status] = @NewStatus,
[Type] = inserted.Type
FROM inserted
WHERE ([id] = inserted.id)
END
我认为正确的解决方案是:
UPDATE myNewTable SET [LastModifiedDate] = GETDATE(),
[Status] = ***<add logic here>***,
[Type] = inserted.Type
FROM inserted
WHERE ([id] = inserted.id)
答案 0 :(得分:1)
你需要这样的东西:
CREATE TRIGGER [dbo].[myTrigger]
ON [dbo].[myTable]
AFTER UPDATE
AS
BEGIN
SET NOCOUNT ON;
UPDATE
myNewTable
SET
LastModifiedDate=GETDATE(),
Status=
CASE
WHEN i.currentStatus IN (1,3,5) THEN 1
WHEN i.currentStatus IN (8,9) THEN 8
WHEN i.currentStatus IN (11,12,13) THEN 11
ELSE NULL -- if the current status isn't in the cases above
END,
Type=i.Type
FROM
myNewTable AS mnt
INNER JOIN inserted AS i ON
i.id=mnt.id;
END