![](/img/trans.png)
[英]How to maintain identity column value during SQL bulk copy to another table?
[英]How to get the Identity values in SQL BULK COPY?
我必須從SQLBULKCOPY之后的表到同一表中獲取IDENTITY值。 數據量可能是數千條記錄。
有人可以幫我嗎?
免責聲明 :我是Bulk Operations項目的所有者
簡而言之,該項目通過添加必須的功能(例如輸出插入的標識值)來克服SqlBulkCopy的限制。
在后台,它使用SqlBulkCopy和類似@Mr Moose答案的方法。
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);
編輯:回答評論
我可以簡單地獲取一個IList還是簡單地將其保存回customers表中,但是沒有變量可以保存它,請您幫忙。 所以,我在Orders.CustomerID表中插入
根據情況,您可以在Order DataTable
保留對名為CustomerRef
的Customer DataRow的引用。
因此,一旦合並了客戶,便可以輕松地從Order DataTable中的CustomerRef
列中填充CustomerID
列。
這是我要說的例子: https : //dotnetfiddle.net/Hw5rf3
嘗試這個
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
-- 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.