Bulk insert with text qualifier in SQL Server

后端 未结 4 418
时光说笑
时光说笑 2020-11-30 13:21

I am trying to bulk insert few records in a table test from a CSV file ,

 CREATE TABLE Level2_import 
 (wkt varchar(max),
 area VARCHAR(40),
 )         


        
4条回答
  •  有刺的猬
    2020-11-30 13:54

    You need to use a 'format file' to implement a text qualifier for bulk insert. Essentially, you will need to teach the bulk insert that there's potentially different delimiters in each field.

    Create a text file called "level_2.fmt" and save it.

    11.0
    2
    1   SQLCHAR   0  8000   "\","      1     wkt         SQL_Latin1_General_CP1_CI_AS
    2   SQLCHAR   0  40   "\r\n"      2     area         SQL_Latin1_General_CP1_CI_AS
    

    The first line, "11.0" refers to your version of SQL. The second line shows that your table, [level2_import], has two columns. Each line after that will describe a column, and obeys the following format:

    [Source Column Number][DataType][Min Size][Max Size][Delimiter pattern][Destination Column Number][Destination Column Name][Case sensitivity of database]

    Once you've created that file, you can read in your data with the following bulk insert statement:

    BULK INSERT level2_import
    FROM 'D:\test.csv'
    WITH 
    (
      FIRSTROW = 2,
      FORMATFILE='D:\level_2.fmt'
    );
    

    Refer to this blog for a detailed explanation of the format file.

提交回复
热议问题