1

我正在尝试将来自多个文件的数据插入 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 '('

我在上面的查询中做错了什么?

4

2 回答 2

3

您不能将变量用作文件名。根据MSDN中描述的语法,它必须是一个常量。

您可以创建命令并使用 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)
于 2013-01-19T15:43:56.517 回答
1

您不能将变量用作表名。如果要使用变量,则必须创建一个字符串并使用如下EXEC函数:

DECLARE @fullname nvarchar, @sql nvarchar
SET @sql = 'SELECT * FROM ' + @fullname+ ' WHERE id = 1'
EXEC(@sql)
于 2013-01-19T15:40:48.693 回答