How to get the Identity values in SQL BULK COPY?

爷,独闯天下 提交于 2019-12-01 10:36:32

问题


I have to get the IDENTITY values from a table after SQLBULKCOPY to the same table. The volume of data could be thousands of records.

Can someone help me out on this ?


回答1:


Disclaimer: I'm the owner of the project Bulk Operations

In short, this project overcomes SqlBulkCopy limitations by adding MUST-HAVE features like outputting inserted identity value.

Under the hood, it uses SqlBulkCopy and a similar method as @Mr Moose answer.

var bulk = new BulkOperation(connection)

// Output Identity Value
bulk.ColumnMappings.Add("CustomerID", ColumnMappingDirectionType.Output);

// Map Column
bulk.ColumnMappings.Add("Code");
bulk.ColumnMappings.Add("Name");
bulk.ColumnMappings.Add("Email");

bulk.BulkInsert(dt);

EDIT: Answer comment

can I simply get a IList or simply , I see its saved back in the customers table, but there is no variable where I can get a hold of it, can you please help with that. So, I an insert in Orders.CustomerID table

It depends, you can keep a reference to the Customer DataRow named CustomerRef in the Order DataTable.

So once you merged your customer, you are able to populate easily a column CustomerID from the column CustomerRef in your Order DataTable.

Here is an example of what I'm trying to say: https://dotnetfiddle.net/Hw5rf3




回答2:


I've used a solution similar to this one from Marc Gravell in that it is useful to first import into a temp table.

I've also used the MERGE and OUTPUT as described by Jamie Thomson on this post to track data I have inserted into my temp table to match it with the id generated by the IDENTITY column of the table I want to insert into.

This is particularly useful when you need to use that ID as a foreign key reference to other tables you are populating.




回答3:


Try this

CREATE TABLE #temp 
(
    DataRow varchar(max)
)
BULK INSERT #Temp FROM 'C:\tt.txt'  

ALTER TABLE #temp
ADD id INT IDENTITY(1,1) NOT NULL

SELECT * FROM #temp



回答4:


-- dummy schema
 CREATE TABLE TMP (data varchar(max))
 CREATE TABLE [Table1] (id int not null identity(1,1), data varchar(max))
 CREATE TABLE [Table2] (id int not null identity(1,1), id1 int not null, data varchar(max))

 -- imagine this is the SqlBulkCopy
 INSERT TMP VALUES('abc')
 INSERT TMP VALUES('def')
 INSERT TMP VALUES('ghi')

 -- now push into the real tables
 INSERT [Table1]
 OUTPUT INSERTED.id, INSERTED.data INTO [Table2](id1,data)
 SELECT data FROM TMP


来源:https://stackoverflow.com/questions/40279338/how-to-get-the-identity-values-in-sql-bulk-copy

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