"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Correctly Cast Variables for Bulk Inserts in T-SQL?

How to Correctly Cast Variables for Bulk Inserts in T-SQL?

Posted on 2025-03-25
Browse:492

How to Correctly Cast Variables for Bulk Inserts in T-SQL?

Casting Variables for Bulk Insert in T-SQL

In T-SQL, the BULK INSERT statement allows data to be imported from an external file into a table. However, if using a string variable as the data source, an error may occur.

Problem:

The following T-SQL code fails with an error (part of a stored procedure):

DECLARE @CSVfile nvarchar(255);
SET @CSVfile = N'T:\x.csv';
BULK INSERT [dbo].[TStagingTable]
-- FROM N'T:\x.csv' -- This line works
FROM @CSVfile -- This line fails
WITH
(
FIELDTERMINATOR = ',',
ROWTERMINATOR = '\n',
FIRSTROW = 2
)

Error message:

Incorrect syntax near the keyword 'with'.

Reason:

In the BULK INSERT statement, the FROM clause requires a literal string as the input file path. When using a variable, it must be cast to a literal string.

Solution:

To cast the variable @CSVfile to a literal string, use the following dynamic T-SQL syntax:

declare @q nvarchar(MAX);
set @q=
    'BULK INSERT [TStagingTable]
    FROM ' char(39) @CSVfile char(39) '
    WITH
    (
    FIELDTERMINATOR = '','',
    ROWTERMINATOR = ''\n'',
    FIRSTROW = 1  
    )'
exec(@q)

This code generates a dynamic SQL statement that casts @CSVfile to a literal string within the FROM clause, resolving the issue and allowing the bulk insert to succeed.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3