2014-04-14 195 views
1

當從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 

但是這給試圖執行上述語句時,下面的錯誤。

消息128,級別15,狀態1,過程titles_in_stock_out,第8行
名稱 「deleted.cd_title」 並不在此上下文中允許的。有效的 表達式是常量,常量表達式和(在某些 上下文中)變量。列名不被允許。

任何幫助?

謝謝

回答

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 

這對於刪除多行的情況會有所幫助。

+0

試過及獲得跟隨着錯誤消息2714,級別16,狀態2,過程titles_in_stock_out,5號線 已經有一個名爲 'titles_in_stock_out' 中的對象數據庫。 – Lalu

+0

嘗試了你的建議,但得到這個錯誤。消息2714,級別16,狀態2,過程titles_in_stock_out,行5 數據庫中已有一個名爲'titles_in_stock_out'的對象。 – Lalu

+1

您的數據庫中已經有名稱爲'titles_in_stock_out'的對象。您可以更改觸發器的名稱,或者如果它是觸發器,則可以使用「更改觸發器」而不是「創建觸發器」。 –

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 
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 
+0

'titles_in_stock'與'titles_in_stock_out'不同。 –

+0

@HamletHakobyan否,但它與目標表相同,並且會得到對象名稱衝突。 – jpw

+0

好的,你說得對。 –

-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 
+0

您可以在同一個insertn中使用values子句和select子句 – HLGEM