用于更新插入行的SQL Server触发器

时间:2016-05-28 10:29:18

标签: sql-server tsql triggers sql-server-2012 sql-update

我想为此创建一个触发器:我有两个表:

表1:

  • id - 整数 - 主键
  • status - 整数 - 值:1表示忙碌,0表示可用

表2:

  • id - 整数 - 主键 - 自动生成
  • id2 - 整数 - NULL或table1
  • 中id的值
  • status - 整数 - 值:1代表工作0等待
  • col1 - 无关的第1列
  • col2 - 无关的第2列
  • col3 - 无关的第3列

当用户这样做时

INSERT INTO table2 (col1, col2, col3)
VALUES (val1, val2, val3);

触发器应检查table1,如果找到并且可用id(status = 0),则更新插入的行table2.id2 = table1.id,table2.status变为1,否则table2.id2保持为NULL,table2.status变为0

现在我尝试了很多方法,并且总是收到错误消息。

这是我最近的尝试:

CREATE TRIGGER myTrigger 
ON table2
AFTER INSERT 
AS
BEGIN
    IF NOT EXISTS (SELECT TOP 1 id 
                   FROM table1
                   WHERE status = 0)
    BEGIN
        UPDATE table2
        SET status = 0
        WHERE table2.id = Inserted.id
    END
    ELSE 
    BEGIN
        SET status = 1
        WHERE table2.id = Inserted.id

        SET table.id@ = (SELECT TOP 1 id 
                         FROM table1
                         WHERE status = 0)
        WHERE table2.id = Inserted.id
    END
END

和错误:

  

Msg 102,Level 15,State 1,Procedure myTrigger,Line 17
  '='附近的语法不正确。

     

第17行:设置状态= 1

     

Msg 156,Level 15,State 1,Procedure myTrigger,Line 22
  关键字'where'附近的语法不正确。

     

第22行:table2.id = Inserted.id

如果您感到慷慨,我需要做的下一件事就是创建一个触发器,当从table2中删除一列时,它会将table1中相应id的状态设置为0(可用)

我正在使用SQL Server 2012

1 个答案:

答案 0 :(得分:3)

您的第二个陈述缺少更新命令:

    set status=1
    where table2.id= Inserted.id
    set table.id@ = (Select TOP 1 id 
                from table1
                where status=0)
    where table2.id= Inserted.id

应该是

    update table2 set table2.status=1,
           table2.id = (Select TOP 1 id 
                from table1
                where status=0)
    join Inserted as i
    on table2.id= Inserted.id;

这应该可以解决您的错误,但是,您的整个触发器可能会被重构为更清晰,但这超出了问题的范围。

相关问题