为什么动态SQL无法与批量插入一起工作?

huangapple go评论58阅读模式
英文:

Why is dynamic SQL not working with bulk insert?

问题

我需要在批量插入查询中使用变量而不是硬编码的文件名,以便通过存储过程的输入参数检索文件名。

我尝试了以下代码:

DECLARE @sql VARCHAR(MAX);
DECLARE @fileDate VARCHAR(100);
DECLARE @filePath VARCHAR(100);

SET @fileDate = CAST(GETDATE() AS date);
SET @filePath = 'D:\BI-SCRIPTS\Nauman\test.csv';

SET @sql = 
    N'BULK INSERT MMBL_phase2.dbo.auto_test' + 'FROM ''' + @filePath + '''' +
    ' WITH(
        FIRSTROW = 2,
        FIELDTERMINATOR = '','',
        ROWTERMINATOR = ''0x0a''
    );';

    EXEC (@sql);

但它会报错:

> Msg 102, Level 15, State 1, Line 5

> 错误的语法附近: 'D:\BI-SCRIPTS\Nauman\test.csv'。

我做错了什么?

英文:

I need to incorporate variables instead of hard-coded file name in bulk insert query so that file name is retrieved through input parameter of a stored procedure.

I tried the following code:

DECLARE       @sql   VARCHAR(MAX);
DECLARE       @fileDate     VARCHAR(100);
DECLARE       @filePath     VARCHAR(100);

SET @fileDate = CAST(GETDATE() AS date);
SET @filePath = 'D:\BI-SCRIPTS\Nauman\test.csv';

SET @sql = 
		N'BULK INSERT MMBL_phase2.dbo.auto_test' + 'FROM ''' + @filePath + '''' +
		' WITH(
			FIRSTROW = 2,
			FIELDTERMINATOR = '','',
			ROWTERMINATOR = ''0x0a''
		);'

		EXEC (@sql);

But it gives the following error:
> Msg 102, Level 15, State 1, Line 5

> Incorrect syntax near 'D:\BI-SCRIPTS\Nauman\test.csv'.

What am I doing wrong?

答案1

得分: 2

你的代码已被修改,动态生成查询时缺少空格。

DECLARE @sql VARCHAR(MAX);
DECLARE @fileDate VARCHAR(100);
DECLARE @filePath VARCHAR(100);

SET @fileDate = CAST(GETDATE() AS date);
SET @filePath = 'D:\BI-SCRIPTS\Nauman\test.csv';

SET @sql = 
    N'BULK INSERT MMBL_phase2.dbo.auto_test' + ' FROM ''' + @filePath + '''' +
    ' WITH (
        FIRSTROW = 2,
        FIELDTERMINATOR = '','',
        ROWTERMINATOR = ''0x0a''
    );';

EXEC (@sql);
英文:

Your code has been modified Missing spaces in dynamically generating query.

DECLARE       @sql   VARCHAR(MAX);
DECLARE       @fileDate     VARCHAR(100);
DECLARE       @filePath     VARCHAR(100);

SET @fileDate = CAST(GETDATE() AS date);
SET @filePath = 'D:\BI-SCRIPTS\Nauman\test.csv';

SET @sql = 
    N'BULK INSERT MMBL_phase2.dbo.auto_test' + ' FROM ''' + @filePath + '''' +
    ' WITH(
        FIRSTROW = 2,
        FIELDTERMINATOR = '','',
        ROWTERMINATOR = ''0x0a''
    );'

    EXEC (@sql);

huangapple
  • 本文由 发表于 2023年7月10日 14:56:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/76651328.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定