Home > Database > Mysql Tutorial > How Can I Efficiently Import a CSV File with Commas and Double Quotes into SQL Server Using BULK INSERT?

How Can I Efficiently Import a CSV File with Commas and Double Quotes into SQL Server Using BULK INSERT?

Linda Hamilton
Release: 2025-01-19 07:20:10
Original
655 people have browsed it

How Can I Efficiently Import a CSV File with Commas and Double Quotes into SQL Server Using BULK INSERT?

Use BULK INSERT to import CSV files into SQL Server

Challenges of handling comma separated data

When importing CSV files into SQL Server using BULK INSERT, handling data that contains commas within fields can be a challenge. To resolve this issue, consider using a different field delimiter, such as the pipe character (|).

Handling double quotes

If the CSV file is exported from Excel, field values ​​containing commas will be enclosed in double quotes. Unfortunately, BULK INSERT cannot handle double quotes directly. As a workaround, you can import the data into the staging table and then use an UPDATE statement to remove the double quotes.

Track invalid rows

To track rows that failed to import due to invalid data, use the ERRORFILE attribute. This property specifies an error file location to which rows that cannot be imported are written. The following modified BULK INSERT statement demonstrates this:

<code class="language-sql">BULK INSERT SchoolsTemp
    FROM 'C:\CSVData\Schools.csv'
    WITH
    (
    FIRSTROW = 2,
    FIELDTERMINATOR = ',',  -- CSV 字段分隔符
    ROWTERMINATOR = '\n',   -- 用于将控制转移到下一行
    ERRORFILE = 'C:\CSVDATA\SchoolsErrorRows.csv',
    TABLOCK
    )</code>
Copy after login

The above is the detailed content of How Can I Efficiently Import a CSV File with Commas and Double Quotes into SQL Server Using BULK INSERT?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template