以下代码给出错误(它是T-sql存储过程的一部分):
-- Bulk insert data from the .csv file into the staging table. 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 will not work WITH ( FIELDTERMINATOR = ',',ROWTERMINATOR = '\n',FIRSTROW = 2 )
错误是:
Incorrect @R_502_156@ near the keyword 'with'.
如果我更换:
FROM @CSVfile
有:
FROM 'T:\x.csv'
那么它的效果很好
解决方法
因为我知道只有字面字符串是必需的.在这种情况下,您必须编写一个动态查询来使用批量插入
declare @q nvarchar(MAX); set @q= 'BULK INSERT [TStagingTable] FROM '+char(39)+@CSVfile+char(39)+' WITH ( FIELDTERMINATOR = '','',ROWTERMINATOR = ''\n'',FIRSTROW = 1 )' exec(@q)