Fire trigger for every inserted row using SqlBulkCopy

余生长醉 提交于 2019-12-01 21:33:54

问题


I am using SqlBulkCopy class to insert 50k rows at a time in table tbl_records I have set a After Insert trigger on this table and using following code

SqlBulkCopy SqlBc1 = new SqlBulkCopy(strConnString, SqlBulkCopyOptions.FireTriggers);

// Set DataReader For SqlBulkCopy

sqlComm = new SqlCommand(strQuery, sqlTemCon);
sqlComm.CommandTimeout = 3600000;
sqlComm.CommandType = System.Data.CommandType.Text;
SqlDataReader dReader = sqlComm.ExecuteReader();       
SqlBc1.WriteToServer(dReader);

But after execution of prog. It fire trigger for only First row out of 50k inserted

I wanna it should fire for every row. How can i do this??


回答1:


Triggers never fire per-row. They fire for all rows of the corresponding DML statement. Rewrite your trigger so that it can cope with the INSERTED table containing many rows. This is best-practice and required practice anyway.

it is firing trigger for only first row inserted out of 50k rows

You must be misinterpreting the situation, maybe because you were unaware that triggers can contain multiple rows in the virtual tables.




回答2:


The SqlBulkCopy object's batch size is the full set of rows, by default.

Here's what MSDN says about the BatchSize property values: "Zero (the default) indicates that each WriteToServer operation is a single batch."

In this case, the trigger will fire once, but the Inserted table will have entries for all of the affected records.




回答3:


I Have try this and it will work for.

I hope its help you..

CREATE TRIGGER Triggername ON TableName After INSERT AS SET NOCOUNT ON;

insert into TargetTable (Fields) SELECT (i.field1,i.field2,i.field3,....,i.fieldn) FROM inserted i GO



来源:https://stackoverflow.com/questions/19002947/fire-trigger-for-every-inserted-row-using-sqlbulkcopy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!