使用触发器复制更新的行值

时间:2019-11-15 17:14:35

标签: sql sql-server

我有一个配置表,我想在更新后放置一个触发器来同步列值。

+----+---------+---------------+-------------+
|type| key     |  value        | dateModified| 
+----+---------+---------------+-------------+
|  1 | MyAPItok|     as7373    | 2019-04-16  |   
|  2 | MyAPItok|     br7345    | 2019-04-12  |   
+----+---------+---------------+-------------+

代码:

CREATE TRIGGER [dbo].[SyncAPITokens]
ON [dbo].[tbl_config]
AFTER UPDATE  
AS 
BEGIN
    UPDATE disp
    SET disp.value = i.[value],
        disp.dateModified = i.[dateModified]
    FROM [dbo].[tbl_config] disp
    INNER JOIN Inserted i ON i.[type] = disp.[type] AND i.[key] = disp.[key] -- use PRIMARY KEY of table!
    WHERE disp.[key] ='MyAPItok'
END

我尝试了几种变体,但似乎无济于事。每当我使用键“ MyAPItok”更新值时,我都希望为具有相同键的每一行分配更新后的值和dateModified。有人知道为什么这行不通吗?

1 个答案:

答案 0 :(得分:0)

使用CTE进行更新

CREATE OR ALTER TRIGGER [dbo].[SyncAPITokens]
ON [dbo].[tbl_config]
AFTER UPDATE  
AS 
BEGIN
    with q as 
    (
      select  disp.*, 
              i.value value_new,
              i.dateModified dateModified_new

      FROM [dbo].[tbl_config] disp
      INNER JOIN Inserted i 
        ON i.[type] = disp.[type] 
        AND i.[key] = disp.[key] -- use PRIMARY KEY of table!
      WHERE disp.[key] = 'MyAPItok'
    )
    --select * from q
    update q set value = value_new, dateModified = dateModified_new;
END

然后您可以切换注释以查看触发器中的结果集以进行调试。您可能会发现触发器实际上并没有执行任何操作。