2017-03-08 67 views
0

我有一個SQL觸發器不會觸發,因爲表中的記錄是通過BULK INSERT插入的。我無法訪問插入記錄的代碼,因此我需要修改此觸發器來處理BULK INSERT。這是觸發器:修改SQL觸發器以使用BULK INSERT

USE [testdata] 
GO 
SET ANSI_NULLS ON 
GO 
SET QUOTED_IDENTIFIER ON 
GO 

ALTER TRIGGER [dbo].[Trigger_test] ON [dbo].[test] 
    AFTER INSERT , UPDATE 
AS 

BEGIN 

    DECLARE @BatchId int, @Ethanol decimal(18,6), @Glucose decimal(18,6), @SampleAge varchar(50); 

    SELECT @BatchId = CONVERT(int,bd.[BatchId]), 
      @Ethanol = CONVERT(decimal(18,2),[Ethanol]), 
      @Glucose= CONVERT(decimal(18,2),[Glucose]), 
      @SampleAge = bd.SampleCode 
    from INSERTED bd 

    update [dbo].[DeSchedule] 
    SET 
      [Ethanol] = @Ethanol, 
      [Glucose] = @Glucose, 
      [SampleCompleted] = 1 
    WHERE [BatchID] = @BatchId AND [SampleAge] = @SampleAge 
END 

任何人都可以幫我修改這個觸發器來處理BULK INSERT。

+3

你的觸發器有一個重大缺陷。它假定插入的表將只有一行。觸發器每行不是每行觸發。而BULK INSERT意味着你幾乎總是會有多行。您需要基於集合的邏輯,而不是標量邏輯。 –

+0

http://stackoverflow.com/questions/19002947/fire-trigger-for-every-inserted-row-using-sqlbulkcopy –

+0

Gaaaaaaaaaaaaaaa。在INSERTED中可能有/多於一行。 (如前所述)。請不要寫「Theres only one row」類型的觸發器。 Gaaaaaaaaaaaaaaa。 – granadaCoder

回答

0

的問題是,它僅選擇插入表格的最後一行,如果你改變這樣的查詢,我認爲這是可行的

update [dbo].[DeSchedule] 
    SET 
      [Ethanol] =(select CONVERT(int,bd.[Ethanol]) from inserted bd), 
      [Glucose] = (select CONVERT(decimal(18,2),[Glucose]) from inserted bd), 
      [SampleCompleted] = 1 
    WHERE [BatchID] = (select CONVERT(int,bd.[BatchId]) from inserted bd) AND [SampleAge] = (select bd.SampleCode from inserted bd)