批量SQL中出现错误'WITH Statement'

时间:2017-01-04 15:58:59

标签: sql sql-server tsql

嗨我遇到了我创建的存储过程的问题。我在'@path'附近语法错误时遇到语法错误

如果我把绝对路径'J:\ TestCSV \ ImportData.csv'我没有收到任何错误。但是,如果我声明参数,我收到了上面提到的这个错误。这是我的存储过程。希望得到你的帮助。

Create PROCEDURE [dbo].[FileUpload]

 As
BEGIN


DECLARE @path VARCHAR(256); -- path   
DECLARE @fileName VARCHAR(256); -- filename   
DECLARE @fileDate VARCHAR(20); -- used for file date
SELECT @fileDate = CONVERT(VARCHAR(20),GETDATE(),112) ;
SET @fileName = 'ImportData' + '_' + @fileDate + '.csv';
SET @path = 'J:\TestCSV\' + @fileName;

BULK

INSERT [dbo].[temp_Cemetery]
--FROM 'E:\CSVTest\ImportDataYYYYMMDD.csv'
FROM @path  -- Error Here Incorrect syntax near '@path'
WITH
(
FIELDTERMINATOR = ',',
ROWTERMINATOR = '\n'
)


END

3 个答案:

答案 0 :(得分:1)

出于某种原因,您必须使用字符串文字。您可能必须使用动态SQL,例如

CREATE PROCEDURE [dbo].[FileUpload]
AS
BEGIN


DECLARE @path VARCHAR(256); -- path   
DECLARE @fileName VARCHAR(256); -- filename   
DECLARE @fileDate VARCHAR(20); -- used for file date
SELECT @fileDate = CONVERT(VARCHAR(20),GETDATE(),112) ;
SET @fileName = 'ImportData' + '_' + @fileDate + '.csv';
SET @path = 'J:\\TestCSV\\' + @fileName;
DECLARE @sql varchar(8000)

SET @sql = 'BULK INSERT [dbo].[temp_Cemetery]
FROM ''' + @path + '''
WITH
(
    FIELDTERMINATOR = '','',
    ROWTERMINATOR = ''\n''
)'

EXEC (@sql)

END

答案 1 :(得分:0)

问题是你需要逃避引号附近的反斜杠:

SET @path = 'J:\\TestCSV\\' + @fileName;

这是因为反斜杠是一个特殊字符,因为您转义了单引号,所以它将该语句的其余部分视为字符串的一部分。我在下面为你修好了。

Create PROCEDURE [dbo].[FileUpload]

 As
BEGIN


DECLARE @path VARCHAR(256); -- path   
DECLARE @fileName VARCHAR(256); -- filename   
DECLARE @fileDate VARCHAR(20); -- used for file date
SELECT @fileDate = CONVERT(VARCHAR(20),GETDATE(),112) ;
SET @fileName = 'ImportData' + '_' + @fileDate + '.csv';
SET @path = 'J:\\TestCSV\\' + @fileName;

BULK

INSERT [dbo].[temp_Cemetery]
--FROM 'E:\CSVTest\ImportDataYYYYMMDD.csv'
FROM @path  -- Error Here Incorrect syntax near '@path'
WITH
(
FIELDTERMINATOR = ',',
ROWTERMINATOR = '\n'
)


END

答案 2 :(得分:0)

您需要在路径中添加引号,以便FROM子句将其读作'J:\TestCSV\ImportData_20170104.csv'而不是J:\TestCSV\ImportData_20170104.csv

Create PROCEDURE [dbo].[FileUpload]

 As
BEGIN


DECLARE @path VARCHAR(256); -- path   
DECLARE @fileName VARCHAR(256); -- filename   
DECLARE @fileDate VARCHAR(20); -- used for file date
SELECT @fileDate = CONVERT(VARCHAR(20),GETDATE(),112) ;
SET @fileName = 'ImportData' + '_' + @fileDate + '.csv';
SET @path = '''J:\TestCSV\' + @fileName +'''';



BULK
INSERT [dbo].[temp_Cemetery]
--FROM 'E:\CSVTest\ImportDataYYYYMMDD.csv'
FROM @path  -- Error Here Incorrect syntax near '@path'
WITH
(
FIELDTERMINATOR = ',',
ROWTERMINATOR = '\n'
)


END