我正在尝试将多个文件中的数据插入SQL Server。这是我正在使用的代码 -
DECLARE @MyCounter int;
DECLARE @Fileprefix nvarchar, @Filesuffix nvarchar, @fullname nvarchar, @Counter_string nvarchar;
SET @MyCounter = 1;
SET @Fileprefix= 'C:\Arvind_gpd\patents\';
SET @Filesuffix='data_corrected.csv';
WHILE (@MyCounter < 10)
BEGIN;
Set @Counter_string= Cast(@MyCounter AS varchar(1) );
Set @fullname = (@Fileprefix+ @Counter_string + @Filesuffix );
BULK INSERT GooglePatentsIndividualDec2012.dbo.patent
FROM @fullname WITH ( DATAFILETYPE = 'char', FIELDTERMINATOR = '^', ROWTERMINATOR = '\n' );
SET @MyCounter = @MyCounter + 1;
END;
GO
但是我收到这些错误消息 -
Incorrect syntax near @fullname. Expecting Integer, String, TEXT_LEX.....
Incorrect syntax near DATAFILETYPE. Expecting SELECT or '('
在上述查询中我做错了什么?
答案 0 :(得分:3)
您不能将变量用作文件名。根据{{3}}中描述的语法,它必须是常量。
您可以创建命令并使用EXEC执行它。
set @Command = 'BULK INSERT GooglePatentsIndividualDec2012.dbo.patent '
set @Command = @Command + 'FROM '''+@fullname+''' WITH ( '
set @Command = @Command + 'DATAFILETYPE = ''char'', '
set @Command = @Command ü 'FIELDTERMINATOR = ''^'', ROWTERMINATOR = ''\n'' )'
EXEC (@Command)
答案 1 :(得分:1)
您不能将变量用作表名。如果要使用变量,则必须创建一个字符串并使用EXEC
函数,如下所示:
DECLARE @fullname nvarchar, @sql nvarchar
SET @sql = 'SELECT * FROM ' + @fullname+ ' WHERE id = 1'
EXEC(@sql)