SQL 服务器:触发器不工作,发件人附近的语法错误

SQL Server : trigger not working, Syntax Error near From

我尝试创建一个触发器,在插入后检查是否插入了 TO_DELETE = 1。如果是,触发器还应检查在另一个 table (test2) 中 USERGROUP_ID 是否与 I.USERGROUP_ID 相同,并且此 table 中的 TO_DELETE 标志是0. 如果是这种情况,触发器将引发错误并回滚事务。

我试了几个小时了,但我找不到我的错误。错误信息是"error near FROM")

CREATE TRIGGER dbo.Test_Trigger
ON  dbo.Test1
AFTER INSERT
AS
BEGIN
    DECLARE @delete_count numeric(1,0),
            @usergroup_count numeric(1,0),
            @email_count numeric(1,0)

    UPDATE T
    SET @delete_count = CASE I.TO_DELETE WHEN 1 THEN 1 ELSE 0 END
    SET @usergroup_count = CASE dbo.Test2.USERGROUP_ID WHEN I.USERGROUP_ID THEN 1 ELSE 0 END
    SET @email_count = CASE dbo.Test2.TO_DELETE WHEN 0 THEN 1 ELSE 0 END

    IF (@delete_count != 0 AND @usergroup_count != 0 AND @email_count != 0)
    BEGIN   
       RAISERROR (50001,11,1) WITH NOWAIT
       ROLLBACK TRANSACTION
    END

    FROM dbo.Test1 AS T
    INNER JOIN INSERTED AS I ON dbo.Test1.USERGROUP_ID = I.USERGROUP_ID
END

你的 sql 中有太多错误,例如不需要的 set 语句,If update 中的条件。试试这个。

CREATE TRIGGER dbo.Test_Trigger
ON dbo.Test1
AFTER INSERT
AS
  BEGIN
      DECLARE @delete_count    NUMERIC(1, 0),
              @usergroup_count NUMERIC(1, 0),
              @email_count     NUMERIC(1, 0)

      UPDATE T
      SET    @delete_count = CASE I.TO_DELETE
                               WHEN 1 THEN 1
                               ELSE 0
                             END,
             @usergroup_count = CASE T.USERGROUP_ID
                                  WHEN I.USERGROUP_ID THEN 1
                                  ELSE 0
                                END,
             @email_count = CASE T.TO_DELETE
                              WHEN 0 THEN 1
                              ELSE 0
                            END
      FROM   dbo.Test1 T
             INNER JOIN INSERTED AS I
                     ON T.USERGROUP_ID = I.USERGROUP_ID

      IF ( @delete_count != 0
           AND @usergroup_count != 0
           AND @email_count != 0 )
        BEGIN
            RAISERROR (50001,11,1) WITH NOWAIT

            ROLLBACK TRANSACTION
        END
  END 

很难弄清楚您真正想在这里做什么,但使用 EXISTS 似乎是一个不错的方法。不太确定您在 post 编写的代码中尝试对所有这些变量做什么,但这可能是您没有 post 的其他功能。我认为这样的事情应该非常接近。

if exists
(
    select *
    from inserted i
    join test2 t on t.PK = i.PK and t.USERGROUP_ID = i.USERGROUP_ID
    where t.TO_DELETE = 0
)
    RAISERROR (50001,11,1) WITH NOWAIT
    --ROLLBACK TRANSACTION
    --I would recommend not putting the rollback in your trigger. If you have some other code
    --that expects this transaction it will throw an exception. Let the exception
    --bubble back up to the application