在触发器内,将原始表中的n行插入到新表中

时间:2019-04-28 13:12:47

标签: sql-server tsql triggers

我有下表:

==OFFICES==
OFFICE INTEGER NOT NULL,
CITY VARCHAR(15) NOT NULL,
REGION VARCHAR(15) NOT NULL,
DIR INTEGER,
OBJECTIVE MONEY,
SALES MONEY

我必须定义一个名为TRIGGER_EX3的触发器。每当将新行插入OFFICES时,它将以下值存储到名为TCONTROL_OFFICES的表中:

==TCONTROL_OFFICES==
INSERTION_DATE DATETIME, --The day the office was inserted
OPERATION VARCHAR(15), --The name of the operation (inserted)
OFFICE INTEGER, --The id of the office (The value of OFFICE in OFFICES)
THE_USER VARCHAR(30) --Name of the user

我的想法是使用while循环(或for循环)将INSERTED的第一行插入TCONTROL_OFFICES,然后从INSERTED删除同一行,并重复进行直到INSERTED为空。但是,看来我无法修改INSERTED。无论如何,它似乎仍然很笨拙。有更好的方法吗?

这是我到目前为止所拥有的:

USE EMPLOYEES
GO
IF(OBJECT_ID ('TRIGGER_EX3', 'TR') IS NOT NULL)
BEGIN
    DROP TRIGGER TRIGGER_EX3;
END
GO
CREATE TRIGGER TRIGGER_EX3 ON OFFICES
AFTER INSERT
AS
BEGIN
    SET NOCOUNT ON
    --CHECK IF THE TABLE EXISTS
    IF EXISTS (SELECT * 
        FROM SYS.TABLES
        WHERE NAME = 'TCONTROL_OFFICES') --IT DOES
    BEGIN
        PRINT 'IT EXISTS';
    END
    ELSE --IT DOESNT
    BEGIN
        CREATE TABLE TCONTROL_OFFICES
        (INSERTION_DATE DATETIME,
        OPERATION VARCHAR(15),
        OFFICE INTEGER,
        THE_USER VARCHAR(30));
    END

    WHILE((SELECT COUNT(*) FROM INSERTED) > 0)
    BEGIN
        INSERT INTO TCONTROL_OFFICES
        VALUES(GETDATE(), 'INSERT', (SELECT OFFICE FROM INSERTED), SUSER_SNAME())

        DELETE TOP (1) FROM INSERTED
    END
END

请记住,插入可以是3行,但也可能是100行以上,因此我不能在要插入的每一行中按1写入1。

1 个答案:

答案 0 :(得分:1)

只需执行INSERT ... SELECT。您根本不需要任何循环。

INSERT INTO tcontrol_offices
            (insertion_date,
             operation,
             office,
             the_user)
            SELECT getdate(),
                   'INSERT',
                   office,
                   suser_sname()
                   FROM inserted;