Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify SQL Trigger to work with BULK INSERT

Tags:

sql

sql-server

I have a SQL Trigger that doesn't fire because the records in the table are inserted through a BULK INSERT. I do not have access to the code that inserts the records so I need to modify this trigger to handle the BULK INSERT. This is the trigger:

    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

Can anyone help me in modifying this trigger to handle the BULK INSERT.

like image 208
llerdal Avatar asked Mar 10 '23 16:03

llerdal


1 Answers

Unless you can modify the BULK INSERT statement you are stuck. By default triggers do NOT run during a bulk insert. You must explicitly turn them on in the command with the FIRE_TRIGGER option.

like image 87
Sean Lange Avatar answered Mar 13 '23 01:03

Sean Lange