更新时的 MSSQL 触发器:支持多行更新
MSSQL trigger on UPDATE: Support multiple row updates
我有一个 SQL 触发器,它在 table 更新时触发。当更新 table 时,它会修改另一个 table 中的某些字段。
它似乎可以正常工作,但我不确定我设置状态的方式是否正确(如果插入的内容包含多行)。我测试了它并得到了正确答案(但我仍然怀疑这不是 correct/best 方式)。
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)
你需要这样的东西:
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
我有一个 SQL 触发器,它在 table 更新时触发。当更新 table 时,它会修改另一个 table 中的某些字段。
它似乎可以正常工作,但我不确定我设置状态的方式是否正确(如果插入的内容包含多行)。我测试了它并得到了正确答案(但我仍然怀疑这不是 correct/best 方式)。
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)
你需要这样的东西:
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