Question

I am using this query in SQL SERVER 2008..

SET IDENTITY_INSERT ABC ON

BULK 
INSERT ABC
FROM 'F:\test.csv'
WITH
(
    FIELDTERMINATOR = ',',
    ROWTERMINATOR = '\n'
)
GO

and getting an error :

Explicit value must be specified for identity column in table 'ABC' either when IDENTITY_INSERT is set to ON or when a replication user is inserting into a NOT FOR REPLICATION identity column.

Table structure for 'ABC' is :

ID [int] IDENTITY(1,1) NOT NULL,  -- primary key
aa [varchar](50) NULL,
bb [varchar](50) NULL,
cc [datetime] NULL,
dd [varchar](50) NULL,
ee [varchar](50) NULL,
ff [int] NULL,
gg [varchar](50) NULL,
ii [int] NULL,
jj [int] NULL

Sample data from CSV file

84,0b0dbe1d,192.168.10.221,2012-07-27 16:15:41.503,0b0dbe1d_16-15-18,1.0.0,2,pra,2,NULL
85,111de4b6,192.168.10.221,2012-07-27 16:27:06.060,111de4b6_16-27-05,1.0.0,8,Diane,5,NULL
Was it helpful?

Solution 2

The error clearly says, you need to specify the column names while inserting.

I don't think we have a option to specify the column names during bulk insert. You can use the below alternative.

 select * into dbo.Stagingtable from ABC where 1=2
    go

    BULK 
    INSERT Stagingtable
    FROM 'F:\test.csv'
    WITH
    (
        FIELDTERMINATOR = ',',
        ROWTERMINATOR = '\n'
    )
    GO
    SET IDENTITY_INSERT ABC ON
GO
    INSERT INto ABC (column1,column2,etc) 
    select * from Stagingtable 

OTHER TIPS

James, you are getting error because your csv file contain 9 column values but your table structure contain 10 columns.. so thats why you are getting that error.. If you SET Identity_Insert ABC off then you will get no error

From Keep Identity Values When Bulk Importing Data (SQL Server):

To prevent SQL Server from assigning identity values while bulk importing data rows into a table, use the appropriate keep-identity command qualifier. When you specify a keep-identity qualifier, SQL Server uses the identity values in the data file. These qualifiers are as follows:

bcp                                          | -E             |  Switch
BULK INSERT                                  | KEEPIDENTITY   |  Argument
INSERT ... SELECT * FROM OPENROWSET(BULK...) | KEEPIDENTITY   |  Table hint

The example shows how to apply this potion in your case:

BULK 
INSERT ABC
FROM 'F:\test.csv'
WITH
(
    KEEPIDENTITY,  
    FIELDTERMINATOR = ',',
    ROWTERMINATOR = '\n'
)
GO
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top