3

我正在使用 SQL Server 2008,并且我有一个触发器,我想将其中的任何行复制My_Table到存档History_Table表中。

每次有人插入新行时,如何将表的整个旧内容复制到存档中?

我的表结构是

    CREATE TABLE [dbo].[Stu_Table]
    (
    [Stu_Id] [int] NOT NULL,
    [Stu_Name] [varchar] (15) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
    [Stu_Class] [int] NULL
    ) ON [PRIMARY]
    GO

ALTER TABLE [dbo].[Stu_Table] ADD CONSTRAINT [PK_Stu_Table] PRIMARY KEY CLUSTERED  ([Stu_Id]) ON [PRIMARY]
GO

我的存档表结构是

CREATE TABLE [dbo].[Stu_TableHistory]
(
[Stu_Id] [int] NOT NULL,
[Stu_Name] [varchar] (15) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[Stu_Class] [int] NULL
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[Stu_TableHistory] ADD CONSTRAINT [PK_Stu_TableHistory] PRIMARY KEY CLUSTERED  ([Stu_Id]) ON [PRIMARY]
GO

我的触发器语法是

Create TRIGGER [dbo].[HistoryKeep]
   ON  [dbo].[Stu_Table]
   INSTEAD OF  INSERT
AS 
BEGIN
    IF((SELECT COUNT(*) FROM Stu_Table WHERE Stu_Id = (SELECT Stu_Id FROM INSERTED)) >= 1)
    BEGIN
        INSERT INTO dbo.Stu_TableHistory( Stu_Id, Stu_Name, Stu_Class )
        SELECT Stu_Id, Stu_Name, Stu_Class FROM Stu_Table WHERE Stu_Id = (SELECT Stu_Id FROM INSERTED)

        UPDATE x
        SET x.Stu_Name = i.Stu_Name
        FROM dbo.Stu_Table AS x
        INNER JOIN inserted AS i ON i.Stu_Id = x.Stu_Id

    END
    ELSE
    BEGIN
        INSERT INTO dbo.Stu_Table( Stu_Id, Stu_Name, Stu_Class )
        SELECT Stu_Id, Stu_Name, Stu_Class FROM INSERTED
    END
END

总之需要帮助将旧数据从学生表传输到存档表。我上面的触发器语法不能满足我。

如果有任何疑问请提前询问。

4

1 回答 1

3

而不是你当前的触发器,你应该有类似的东西:

Create TRIGGER [dbo].[HistoryKeep]
   ON  [dbo].[Stu_Table]
   INSTEAD OF  INSERT
AS 
BEGIN
DECLARE @History table (
    Action sysname not null,
    STU_ID [int] NULL,
    [Stu_Name] [varchar] (15) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
    [Stu_Class] [int] NULL
)

;MERGE INTO Stu_Table t
USING INSERTED i ON t.STU_ID = i.STU_ID
WHEN MATCHED THEN UPDATE SET STU_Name = i.STU_Name
WHEN NOT MATCHED THEN INSERT (STU_ID,STU_NAME,STU_CLASS) VALUES (i.STU_ID,i.STU_NAME,i.STU_CLASS)
OUTPUT $Action,deleted.stu_id,deleted.stu_name,deleted.stu_class INTO @History;

INSERT INTO stu_TableHistory (stu_id,stu_name,stu_class)
select stu_id,stu_name,stu_class from @History where Action='UPDATE'
END

另请注意,您需要将当前的 PK 约束放在 上STU_TableHistory,因为只要一行更新不止一次,就会有两个条目包含相同的STU_ID.


根据我的评论,这被视为INSERTED一个包含多行的表格。因此,如果Stu_Table包含 1 的行STU_ID,则插入以下内容:

INSERT INTO STU_Table (STU_ID,STU_Name,STU_Class) VALUES
(1,'abc',null),
(2,'def',null)

更新STU_ID1的行,为2 插入一行,并( for 1)中插入一行STU_IDstu_tableHistorySTU_ID

于 2013-01-15T09:11:53.183 回答