通过SQL Server中的触发器更新多行

时间:2019-03-12 10:40:04

标签: sql-server triggers

如果fld_IsUpdated设置为true,则使用下面的触发器更新行。

ALTER TRIGGER [dbo].[UpdateFieldDate_GroupChat] ON [dbo].[tbl_GroupChat]
AFTER UPDATE
AS
     SET NOCOUNT ON;
     IF
     (
         SELECT i.fld_IsUpdated
         FROM inserted i
     ) = 1
         BEGIN
             DECLARE @now BIGINT= (CONVERT([BIGINT], replace(replace(replace(CONVERT([VARCHAR](19), GETDATE(), (121)), ':', ''), '-', ''), ' ', ''), (0)));
             UPDATE tbl_GroupChat
               SET 
                   tbl_GroupChat.fld_ModifiedAt = @now
             WHERE tbl_GroupChat.fld_Id =
             (
                 SELECT i.fld_Id
                 FROM inserted i
             );
     END;

当我执行诸如UPDATE tbl_GroupChat SET fld_IsUpdated = 1;之类的更新查询时,SSMS显示以下错误:

Msg 512, Level 16, State 1, Procedure UpdateFieldDate_GroupChat, Line 5 [Batch Start Line 0]
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
The statement has been terminated.

我测试了许多触发器结构,但是它们都有相同的错误,例如下面的代码,我没有声明变量:

 tbl_GroupChat.fld_ModifiedAt = (CONVERT([BIGINT], replace(replace(replace(CONVERT([VARCHAR](19), GETDATE(), (121)), ':', ''), '-', ''), ' ', ''), (0)))

1 个答案:

答案 0 :(得分:1)

在这里:

IF
     (
         SELECT i.fld_IsUpdated
         FROM inserted i
     ) = 1

将fld_IsUpdated与1进行比较。但是,inserted表具有多个行,因此select是整个表。表不能与单个值进行比较。

尝试一下:

ALTER TRIGGER [dbo].[UpdateFieldDate_GroupChat] ON [dbo].[tbl_GroupChat]
AFTER UPDATE
AS
    SET NOCOUNT ON;

    BEGIN
        DECLARE @now BIGINT= (CONVERT([BIGINT], replace(replace(replace(CONVERT([VARCHAR](19), GETDATE(), (121)), ':', ''), '-', ''), ' ', ''), (0)));

        UPDATE t 
        SET tbl_GroupChat.fld_ModifiedAt = @now
        FROM tbl_GroupChat as t
        INNER JOIN inserted i ON t.fld_Id=i.fld_Id
        WHERE i.fld_IsUpdated=1
     END;