使用目标表标识列进行批量插入

Rob*_*ack 4 c# sql-server c#-3.0 c#-4.0

我正在尝试从DataTableSQL Server 中的表中批量插入,但在我的数据表中没有 id 列。当我调用该WriteToServer方法时,它会抛出异常并显示消息

无法在列 id 中插入 null

代码:

CREATE TABLE [dbo].[TBL_HISTORY]
(
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [VAR1] [int] NOT NULL,
    [VAR2] [datetime] NOT NULL,
    [VAR3] [smallint] NOT NULL
)
Run Code Online (Sandbox Code Playgroud)

我的数据表有以下数据

[VAR1], [VAR2], [VAR3]
Run Code Online (Sandbox Code Playgroud)

C#代码:

using(SqlBulkCopy bulk = new SqlBulkCopy(this.mConnection,SqlBulkCopyOptions.UseInternalTransaction | SqlBulkCopyOptions.KeepIdentity, null))
{
    bulk.DestinationTableName = ToTable;

    bulk.WriteToServer(dt);    // here exception is thrown
}
Run Code Online (Sandbox Code Playgroud)

小智 6

您需要删除 SqlBulkCopyOptions.KeepIdentity 选项。您告诉它使用您提供的身份,但没有身份,也称为空。

https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlbulkcopyoptions%28v=vs.110%29.aspx

保持身份

保留源标识值。如果未指定,标识值由目标分配。