BULK插入参数化FIRSTROW

时间:2014-05-17 13:06:32

标签: sql sql-server bulkinsert

有没有办法在BULK INSERT QUERY中参数化FIRSTROW

这是我的选择陈述 SELECT TOP 1 mid from movie_titles ORDER BY mid DESC

返回整数值,我想在批量插入语句中提供其结果

BULK
INSERT movie_titles
FROM 'A:\Netflix\movie_titles.txt'
WITH
(
FIRSTROW = 'here i want to provide the result of above select query',
FIELDTERMINATOR = ',',
ROWTERMINATOR = '\n'
)

2 个答案:

答案 0 :(得分:2)

无法为FIRSTROW提供@variable名称。如果要这样做,则需要通过字符串连接动态创建BULK INSERT语句,并使用EXEC或sp_execute执行它。

答案 1 :(得分:2)

AFAIK,您无法直接将参数传递给FIRSTROW。相反,您可以将BULK INSERT作为动态SQL执行,如下所示( 未经过测试 ,但这会让您入门)

DECLARE @midvar INT;
SELECT TOP 1 @midvar = cast(mid as INT) from movie_titles ORDER BY mid DESC;
DECLARE @bulk_cmd varchar(1000);
SET @bulk_cmd = 'BULK INSERT movie_titles
FROM ''A:\Netflix\movie_titles.txt'' 
WITH (ROWTERMINATOR = '''+CHAR(10)+'' +
'FIELDTERMINATOR ='',''
FIRSTROW = ' + @midvar + ')';
EXEC(@bulk_cmd);