views:

42

answers:

2

On bulk insert, Insert trigger only works for the first record and does not work for all the other records but trigger works properly when records are inserted using cursor.

Insert trigger updates few columns of destination table. To insert bulk data I am using following script

INSERT INTO DestinationTable (Column1, Column2)
SELECT * FROM SourceTable

I get few columns in trigger of inserted record like the following script, and work on them to update columns of DestinationTable

SELECT @col1 = Column1, @col2 = Column2, FROM INSERTED
  1. Why on bulk insert, trigger does not work?
  2. Am I missing something or I have to use cursor?

I am using SQLServer 2005

EDIT

Trigger Code

http://stashbox.org/957108/InsertTrigger.sql

Thanks.

A: 

Well on cursor it is because each record is being inserted one at a time and not in a batch. So with bulk insert they insert in a batch. So the trigger fires once for the batch.

I think I read about a workaround one time that was pretty clean. Let me see if I can find it.

EDIT: You know when you said bulk operation I didn't even pay attention to the sql and assumed you were using bcp. But I do still remember a work around that I am going to look for.

EDIT2: Ok take a look at this article and see if it helps you out: http://weblogs.sqlteam.com/tarad/archive/2004/09/14/2077.aspx

spinon
Thanks @spinon, if you can find it that would be great help.
Muhammad Kashif Nadeem
Thanks for the link spinon.
Muhammad Kashif Nadeem
A: 

From the code you posted it looks like by bulk insert you just mean inserting multiple rows. Not this BULK INSERT?

The INSERTED pseudo table contains all the rows inserted by the statement. It is not a row level trigger. You would need to use a cursor for RBAR processing or, ideally, process it as a set. For example if you are Updating another table you could join onto the inserted table and update all the rows in one statement.

Martin Smith
Thanks Martin, can you please elaborate this; process it as a set?
Muhammad Kashif Nadeem
SourceTable has 10K rows and I want to insert all in DestinationTable in one go and also want Insert Trigger to update each row.
Muhammad Kashif Nadeem
Can you post your trigger code?
Martin Smith
I have uploaded trigger script. Please see my edit in question. It would be really great if you mention other mistakes too while going through it.
Muhammad Kashif Nadeem
All looks good to me. Was quite a bit longer than I was expecting! Basically in order to get your trigger working against multiple rows you could just use a cursor and process each row in the way you are currently doing or you would need to replace the parts where it is currently populating a scalar variable per row so that it works for multiple rows. Maybe you could begin by using table variables instead of scalar variables then try and combine some of the steps.
Martin Smith
Thanks Martin. Great help. Really appreciate it.
Muhammad Kashif Nadeem