在MSSQL中INSERT触发器:按变量的目标表

时间:2014-09-18 09:19:14

标签: sql sql-server triggers

多个程序/进程将其历史记录插入一个(非常大的)历史记录表(tbl_History)中。我无法改变这一点。我必须将它们分类为"对"插入历史表。这些不同的历史表已经存在。那时我不会创造。但是通过参数" his_ID"我可以检查一下,女巫桌是正确的目的地表。

所以我在这个表中添加了一个触发器。这个有效:

CREATE TRIGGER [dbo].[Trigger_tbl_History_Insert]
ON [dbo].[tbl_History]
AFTER INSERT
AS
BEGIN

    INSERT INTO [tbl_Historyef33894e-3fda-4833-b1e6-efa5cb9ce8ee] SELECT * FROM inserted;
END

但现在我想通过新插入行中的变量来决定目标表。我想是这样的:

CREATE TRIGGER [dbo].[Trigger_tbl_History_Insert]
ON [dbo].[tbl_History]
AFTER INSERT
AS

BEGIN
    DECLARE @hisID varchar(max);
    SELECT @hisID = inserted.his_ID FROM inserted;
    INSERT INTO [tbl_History + @hisID ] SELECT * FROM inserted;
END

显然这种方式不起作用。 :-)有没有办法实现这个目标?

以下方法无法完全正常运行:

CREATE TRIGGER [dbo].[Trigger_tbl_History_Insert]
ON [dbo].[tbl_History]
AFTER INSERT
AS

BEGIN
    DECLARE @hisID varchar(max);
    SELECT @hisID = inserted.his_ID FROM inserted;
    EXEC ('INSERT INTO tbl_History' + @hisID + '  SELECT * FROM inserted');
END

创建错误:"''"

附近的语法不正确
CREATE TRIGGER [dbo].[Trigger_tbl_History_Insert]
ON [dbo].[tbl_History]
AFTER INSERT
AS

BEGIN
    DECLARE @hisID varchar(max);
    SELECT @hisID = inserted.his_ID FROM inserted;
    EXEC ('INSERT INTO [tbl_History' + @hisID + ']  SELECT * FROM inserted');
END

创建错误:"无效的对象名称'已插入'。"

2 个答案:

答案 0 :(得分:3)

好吧,我假设名为 [tbl_History123] 的表存在,其中123是变量@hisID。所以在这种情况下你可以这样做 -

CREATE TRIGGER [dbo].[Trigger_tbl_History_Insert]
ON [dbo].[tbl_History]
AFTER INSERT
AS

BEGIN
    DECLARE @hisID varchar(max);
    SELECT @hisID = inserted.his_ID FROM inserted;

    EXEC ('INSERT INTO tbl_History' + @hisID + '  SELECT * FROM inserted');

    -- OR you can also do this
    EXEC (
        'SELECT * 
         INTO tbl_History' + @hisID + '
         FROM inserted'
        );

END

EDITED

好的,请使用与[tbl_History123]相同的架构制作另一个单独的表格 - tmpHistoryForID 。这适用于中介表。所以在触发器中首先将数据插入此表,然后从此表插入到[tbl_History123]表中。像这样 -

CREATE TRIGGER [dbo].[Trigger_tbl_History_Insert]
    ON [dbo].[tbl_History]
    AFTER INSERT
    AS

BEGIN
        DECLARE @hisID varchar(max);
        SELECT @hisID = inserted.his_ID FROM inserted;

        INSERT INTO dbo.tmpHistoryForID 
            SELECT * FROM inserted

        EXEC ('INSERT INTO tbl_History' + @hisID + '  SELECT * FROM dbo.tmpHistoryForID');

        TRUNCATE TABLE dbo.tmpHistoryForID

END

答案 1 :(得分:0)

您无法使用动态SQL查询访问魔术表。在执行动态查询之前,将记录放入临时表中。以下是触发器的代码。

CREATE TRIGGER [dbo].[Trigger_tbl_History_Insert]
ON [dbo].[tbl_History]
AFTER INSERT
AS

BEGIN
    DECLARE @ID int;
    DECLARE @Qry varchar(max)
    SELECT @ID = inserted.ID FROM inserted;
    select * into #tmp from inserted
    SET @Qry=CONCAT('INSERT INTO tbl_History' , @ID ,'  SELECT * FROM #tmp')
    EXEC (@Qry)
END