transact-sql newbie-error-尝试将数据从多个文件批量插入sql server数据库

时间:2013-01-19 15:27:23

标签: sql sql-server sql-server-2008 sql-server-2008-r2

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

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

2 个答案:

答案 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)