删除后创建触发器

时间:2014-04-14 11:51:36

标签: sql sql-server

当从titles_in_stock表中删除行时,我想在名为titles_in_stock_out的表中插入等效行。

我尝试了以下

create trigger titles_in_stock_out
   on titles_in_stock
   after delete as
   begin
      insert into titles_in_stock_out
      (cd_title, invenotry, cd_type)
      values
      (deleted.cd_title, deleted.invenotry, deleted.cd_type)
   end

但是在尝试执行上述语句时会出现以下错误。

  

Msg 128,Level 15,State 1,Procedure titles_in_stock_out,Line 8
  名称" deleted.cd_title"在这种情况下是不允许的。有效   表达式是常量,常量表达式和(在某些情况下)   上下文)变量。不允许使用列名。

任何帮助?

由于

4 个答案:

答案 0 :(得分:6)

您的语法不正确。 deleted是虚拟表,在触发器中可用,然后您必须将其作为表引用。

create trigger titles_in_stock_out
   on titles_in_stock
   after delete as
   begin
      insert into titles_in_stock_out
      (cd_title, invenotry, cd_type)
      select cd_title, invenotry, cd_type
      from deleted
   end

如果您删除了多行,这将非常有用。

答案 1 :(得分:1)

您需要将deleted称为表格,并且触发器需要具有不同的名称;在您的示例中,它与表格具有相同的名称。

create trigger titles_in_stock_out_trig
   on titles_in_stock
   after delete as
   begin
      insert into titles_in_stock_out
      (cd_title, invenotry, cd_type)
      select 
      cd_title, invenotry, cd_type
      from deleted
   end

答案 2 :(得分:0)

    create trigger titles_in_stock_out
       on titles_in_stock
       FOR  delete 
       begin
   insert into titles_in_stock_out
      (cd_title, invenotry, cd_type)
      select 
      cd_title, invenotry, cd_type
      from deleted
       end

答案 3 :(得分:-1)

这可以解决您的问题:

IF OBJECT_ID('titles_in_stock_out', 'TR') IS NOT NULL
DROP TRIGGER titles_in_stock_out
GO
CREATE TRIGGER titles_in_stock_out
ON titles_in_stock
FOR DELETE 
AS
BEGIN
      INSERT INTO titles_in_stock_out
      (cd_title, invenotry, cd_type)
      VALUES
      (cd_title, invenotry, cd_type)
      SELECT 
      cd_title, invenotry, cd_type
      FROM titles_in_stock
END