以下代码给出错误(它是 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 syntax near the keyword 'with'.
如果我更换:
FROM @CSVfile
与:
FROM 'T:\x.csv'
...然后就可以很好地工作了。
据我所知,from 中需要一个文字字符串。在这种情况下,您必须编写动态查询才能使用批量插入
declare @q nvarchar(MAX);
set @q=
'BULK INSERT [TStagingTable]
FROM '+char(39)+@CSVfile+char(39)+'
WITH
(
FIELDTERMINATOR = '','',
ROWTERMINATOR = ''\n'',
FIRSTROW = 1
)'
exec(@q)
您尝试过动态 SQL 吗?
SET @SQL = "BULK INSERT TmpStList FROM '"+@PathFileName+"' WITH (FIELDTERMINATOR = '"",""') "
然后
EXEC(@SQL)
参考:http://www.sqlteam.com/article/using-bulk-insert-to-load-a-text-file
你必须参与字符串构建,然后调用 EXEC() 或 sp_executesql BOL 有一个例子:
DECLARE @bulk_cmd varchar(1000)
SET @bulk_cmd = 'BULK INSERT AdventureWorks2008R2.Sales.SalesOrderDetail
FROM ''<drive>:\<path>\<filename>''
WITH (ROWTERMINATOR = '''+CHAR(10)+''')'
EXEC(@bulk_cmd)
大多数时候,我在文件名中查找的变量是日期,而这个变量非常适合批量插入带有日期的文件,例如在日常工作中使用。根据您的需要更改日期格式、表名、文件路径、文件名和分隔符。
DECLARE @DT VARCHAR (10)
DECLARE @INSERT VARCHAR (1000)
SET @DT = (CONVERT(VARCHAR(10),GETDATE()-1,120))
SET @INSERT = 'BULK INSERT dbo.table FROM ''C:\FOLDER\FILE'+@DT+'.txt'''+' WITH (FIRSTROW=2, FIELDTERMINATOR=''\t'', ROWTERMINATOR=''\n'')'
EXEC (@INSERT);
你可以尝试吗
FROM ' + @CSVfile + '