在触发器中插入已删除的行

时间:2012-10-16 14:04:21

标签: sql-server-2005 triggers

我需要将表Table_A中删除的行插入到具有相同结构的表_B中 (类似于回收站)但我没有太多SQL SERVER触发器的经验

CREATE TRIGGER dbo.Table_A_Delete_Instead_Of_Trigger
ON dbo.Table_A
INSTEAD OF DELETE
AS
BEGIN    
     INSERT INTO Table_B 
     SELECT T 

     DELETE T                  
END
请保留我的经验。感谢。

2 个答案:

答案 0 :(得分:6)

你不需要'INSTEAD OF'触发器,你需要一个'AFTER'触发器。

给出表格表格......

CREATE TABLE [dbo].[TableA](
    [Col1] [varchar](50) NOT NULL,
    [Col2] [varchar](50) NOT NULL
) ON [PRIMARY]

和相应的TableB ......

CREATE TABLE [dbo].[TableB](
    [Col1] [varchar](50) NOT NULL,
    [Col2] [varchar](50) NOT NULL
) ON [PRIMARY]

然后以下触发器将按您的意愿执行:

CREATE TRIGGER trg_TableA_Archive 
ON  TableA
AFTER DELETE
AS 

    INSERT INTO TableB
    SELECT *
    FROM deleted
GO

答案 1 :(得分:2)

试试这个:

CREATE TRIGGER dbo.Table_A_Delete_Instead_Of_Trigger
ON dbo.Table_A
AFTER DELETE
AS
BEGIN    
     INSERT INTO Table_B 
     SELECT * FROM 
     DELETED;          
END

我认为在这种情况下你不需要使用触发器。