SqlBulkCopy is not inserting rows in same order from the .net DataTable to Sql table in Sql Server

你离开我真会死。 提交于 2019-12-13 09:34:58

问题


objDataTable=ConversionClass.ConvertToDataTable(strFilePath,"tbl_transactonData", ",");       String strConnectionString =ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString;

        SqlBulkCopy bulkCopy = new SqlBulkCopy(strConnectionString);
        bulkCopy.DestinationTableName = "tbl_AllTransactiondata";
        try
        {
            bulkCopy.WriteToServer(objDataTable);
        }
        catch (Exception ex)
        {

        }
        finally
        {
            bulkCopy.Close();
        }

I need to transfer value from datatable to Sql Table using SqlBulkCopy. But SqlBulkCopy is not inserting rows in proper order .Please suggest solution for the same.


回答1:


Typically there is no guaranteed order for bulk insert operations. Besides inserting each row individually (neither fun nor efficient), you might could try using the TableLock SqlBulkCopyOption.

new SqlBulkCopy(strConnectionString, SqlBulkCopyOptions.TableLock);

It will attempt a minimally-logged operation which can only be done via an ordered insert, which will be done via a background sort in tempdb first.




回答2:


You could use the order by clause in sql. Of course this assumes that your data is already sorted by one column. https://msdn.microsoft.com/en-us/library/ms188385.aspx?f=255&MSPPError=-2147217396

You could create a new table that is a sorted version of the old table after you have completed all of the inserts. Again, same assumption. How to sort values in columns and update table?

You could insert one row at a time with a foreach loop. You would also need to create a DataRow[] of one row each time. https://msdn.microsoft.com/en-us/library/ac44f8yy(v=vs.110).aspx

The ideal solution in my mind is either using the order by clause or sorting it after all of the insertions. Unfortunately, I couldn't find any way to guarantee it would insert rows sequentially.

Class description: https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlbulkcopy(v=vs.110).aspx



来源:https://stackoverflow.com/questions/36507711/sqlbulkcopy-is-not-inserting-rows-in-same-order-from-the-net-datatable-to-sql-t

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