SQL won't insert null values with BULK INSERT

后端 未结 2 1465
难免孤独
难免孤独 2020-12-19 02:01

I have a CSV file and each line looks similar to this:

EASTTEXAS,NULL,BELLVILLE AREA,NULL,BELLVILLE AREA,RGP,NULL,NULL,0,NULL,NULL,NULL,1,1,PM,PM Settings,NU         


        
2条回答
  •  借酒劲吻你
    2020-12-19 03:02

    A late PS.

    Note that there seems to be a bug if the last column is a DATETIME type and the value is null, then you MUST have a (normally superfluous but accepted) field separator after the empty field, before the line-separator, or you'll get an error.

    ADD: This does not consistently work (sometimes it does though!?!?), to make it stable change your ROWterminator to begin with the FIELDterminator

    e.g. FIELDTERMINATOR = '#', ROWTERMINATOR = '#\n'

    Below an example of the error you get when it messes things up:

    Bulk load data conversion error (type mismatch or invalid character for the specified codepage) for row 1, column 31 (MyDateTimeField).

    (And yes I tried an all ASCII example with less than 7F chars and got the same)

    Example:

    The first bulks fails a lot. The other fails on the fifth only, despite the similarity with the second, but nothing is allowed at the end in this special case...

    Test data:

    1#2017-06-13 19:00:11.247#0##2017-06-13 19:00:11.247#
    2#2017-06-13 19:09:08.817#0##2017-06-13 19:00:11.247#123#
    3#2017-06-13 18:44:07.980#1###
    4#2017-06-13 09:39:18.367#11## #
    5#2017-06-13 09:39:18.370#4###123#
    

    and sql

    CREATE TABLE TEST_Bulk(
        id int,
        ts1 datetime,
        txt varchar(40) NULL,
        ts2 datetime,
        ts3 datetime,
    ) 
    GO
    
    BULK INSERT TEST_Bulk FROM 'D:\File.txt' WITH (FIRSTROW=1, FIELDTERMINATOR = '#', ROWTERMINATOR = '\n', CODEPAGE= 'ACP' ,TABLOCK)
    
    BULK INSERT TEST_Bulk FROM 'D:\File.txt' WITH (FIRSTROW=1, FIELDTERMINATOR = '#', ROWTERMINATOR = '#\n', CODEPAGE= 'ACP' ,TABLOCK)
    
    select * from TEST_Bulk
    
    drop table TEST_Bulk
    

提交回复
热议问题