We can use SqlBulkCopy class to bulk copy data. The ColumnMapping property returns a collection of SqlBulkCopyColumnMapping items. If the data source and the destination table have the same number of columns, and the ordinal position of each source column within the data source matches the ordinal position of the corresponding destination column, the ColumnMappings collection is unnecessary. However, if the column counts differ, or the ordinal positions are not consistent, you must use ColumnMappings to make sure that data is copied into the correct columns.
Here is the code sample:
- public void getdata_mstoms(string[,] columlist,string D_Conn, string D_Table,DataTable dt)
- {
- using (SqlConnection cn = new SqlConnection(D_Conn))
- {
- cn.Open();
- using (SqlBulkCopy copy = new SqlBulkCopy(cn))
- {
- for (int i = 0; i < columlist.Length / 2; i++)
- {
- if (columlist[i, 1] != null)
- {
- copy.ColumnMappings.Add(columlist[i, 0].ToString(), columlist[i, 1].ToString());
- }
- }
- copy.DestinationTableName = D_Table;
- copy.WriteToServer(dt);
- }
- }
- }