简体   繁体   中英

Bulk insert with destination table identity column

I'm trying to do a bulk insert from a DataTable into a table in SQL Server, but in my datatable I don't have an id column. When I call the WriteToServer method, it throws an exception with the message

cannot insert null in column id

Code:

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

AND my dataTable has the following data

[VAR1], [VAR2], [VAR3]

C# code:

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

    bulk.WriteToServer(dt);    // here exception is thrown
}

You need to remove the SqlBulkCopyOptions.KeepIdentity option. You are telling it to use the identity that you provide and there is none, aka null.

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

KeepIdentity

Preserve source identity values. When not specified, identity values are assigned by the destination.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM