Sql-Server

觸發器在執行時在 SQL Server 2012 中不起作用?

  • May 18, 2020

在 SQL Server 2012 中,

  1. 我創建了兩個表TABLE1TABLE2
  2. 之後,我創建了一個觸發器TABLE1
  3. 觸發器名稱:PUSH_TABLE2
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE TRIGGER [dbo].[PUSH_TABLE2]
   ON [dbo].[TABLE1]
   AFTER INSERT
AS
BEGIN
   DECLARE @col1 VARCHAR(20), @col2 VARCHAR(20), @col3 VARCHAR(20)
   SELECT @col1=column1, @col2=column2, @col3=column3 FROM INSERTED

   SET NOCOUNT ON;

   INSERT INTO [dbo].[TABLE2] VALUES (@col1, @col2, @col3);

END
  1. 創建觸發器後PUSH_TABLE2,我手動使用下面的插入查詢進行測試TABLE1,觸發器完美地工作,並將數據填充到TABLE1TABLE2
INSERT INTO TABLE1 VALUES('session1', 'value1', 'type1');

(1) rows affected.

(1) rows affected.

問題是如果數據是通過應用程序填充的,它只會填充數據TABLE1,似乎觸發器不起作用。是因為我的觸發腳本問題嗎?

問題是您的觸發器只處理單行插入。在 SQL Server 2008 和 SQL Server 2012 中都是如此。

給定兩個表:

CREATE TABLE dbo.Table1
(
   col1 varchar(20) NULL,
   col2 varchar(20) NULL,
   col3 varchar(20) NULL
);

CREATE TABLE dbo.Table2
(
   col1 varchar(20) NULL,
   col2 varchar(20) NULL,
   col3 varchar(20) NULL
);

處理多行插入的觸發器是:

CREATE TRIGGER dbo.PushTable2
ON dbo.Table1
AFTER INSERT
AS
BEGIN
   SET ROWCOUNT 0;
   SET NOCOUNT ON;

   IF EXISTS (SELECT * FROM Inserted)
   BEGIN
       INSERT dbo.Table2
       (
           col1, 
           col2, 
           col3
       )
       SELECT 
           INS.col1,
           INS.col2,
           INS.col3
       FROM Inserted AS INS
   END;
END;

測試它:

INSERT dbo.Table1
   (col1, col2, col3)
VALUES
   ('session1', 'value1', 'type1');

INSERT dbo.Table1
   (col1, col2, col3)
VALUES
   ('session2', 'value2', 'type2'),
   ('session3', 'value3', 'type3');

SELECT * FROM dbo.Table1 AS T1;
SELECT * FROM dbo.Table2 AS T2;

結果:

結果

引用自:https://dba.stackexchange.com/questions/131460