To copy data from one database to another in different server with same schema, I am planning to use SqlBulkCopy class from C sharp library. Whether SqlBulkCopy will maintain the same order as it is in the datatable while inserting the records ?
Example: id is the identity column.
Server1, db1
TableA
id name
1 name10
2 name20
3 name30
4 name40
Server2, db1
TableA
id name
1 name1
2 name2
3 name3
4 name4
..........
..........
5000 name22
5001 name33
var dt = select * from server1.dbo.TableA order by id;
bulkCopy.WriteToServer(dt);
var resultDt = select top 4 id from server2.dbo.TableA order by id desc.
Since we know the number of records we inserted I am using "top 4".resultDt.DefaultView.Sort = "id asc";
Question: Whether id in resultDt will represent id in dt for all the rows ? i.e,.
5002 from server2 = 1 from server1
5003 from server2 = 2 from server1
5004 from server2 = 3 from server1
5005 from server2 = 4 from server1
Note: Just for example purpose I have given less records. Actual table contains some thousands of records.
答案 0 :(得分:1)
看来批量插入时无法保证订单。所以我在目标表中添加了一个临时id列。流程如下:
Step1: var dt = select *, id as tempId from server1.dbo.TableA order by id;
Step2: SQL bulk copy into server2 bulkCopy.WriteToServer(dt);
Step3: var resultDt = select top 4 id, tempId from server2.dbo.TableA order by id desc. Since we know the number of records we inserted I am using "top 4".
现在id将是server2生成的新id,tempId将是server1的id。问题解决了:))
答案 1 :(得分:0)
另一种解决方案可在以下链接中找到: