Home > Database > Mysql Tutorial > How to Efficiently Import CSV Files into SQL Server Using BULK INSERT and Handle Common Issues?

How to Efficiently Import CSV Files into SQL Server Using BULK INSERT and Handle Common Issues?

Mary-Kate Olsen
Release: 2025-01-19 07:38:09
Original
612 people have browsed it

How to Efficiently Import CSV Files into SQL Server Using BULK INSERT and Handle Common Issues?

Use BULK INSERT to import CSV files into SQL Server

Using BULK INSERT to import CSV files into SQL Server is a common operation, but you may encounter unexpected challenges. This article details how to resolve these issues:

1. Processing commas in CSV data

To handle commas in field values, use a different field separator. For example:

<code class="language-sql">BULK INSERT SchoolsTemp
FROM 'C:\CSVData\Schools.csv'
WITH
(
    FIRSTROW = 2,
    FIELDTERMINATOR = '||',  -- 将分隔符更改为 '||' (管道符)
    ROWTERMINATOR = '\n',
    TABLOCK
)</code>
Copy after login

2. Handling double quotes in Excel

Unfortunately, BULK INSERT cannot handle double quotes containing data. After importing the data, use the SQL statement to remove the quotes:

<code class="language-sql">UPDATE SchoolsTemp
SET Description = REPLACE(Description, '"', '')</code>
Copy after login

3. Tracking error data

To track invalid data rows that were skipped during the import process, use the ERRORFILE attribute:

<code class="language-sql">BULK INSERT SchoolsTemp
FROM 'C:\CSVData\Schools.csv'
WITH
(
    FIRSTROW = 2,
    FIELDTERMINATOR = '||',
    ROWTERMINATOR = '\n',
    ERRORFILE = 'C:\CSVData\SchoolsErrorRows.csv',
    TABLOCK
)</code>
Copy after login

Lines containing errors will be written to the specified error file.

The above is the detailed content of How to Efficiently Import CSV Files into SQL Server Using BULK INSERT and Handle Common Issues?. 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