DECLARE @sqlCommand VARCHAR(MAX) DECLARE @NAME varchar (100)
DECLARE @FIRSTROW INT,@LASTROW INT
SET @FIRSTROW =
(SELECT TOP 1 [Id]
FROM [dbo].[TableB]
ORDER BY [Id] DESC) + 1
SET @LASTROW = @FIRSTROW + 4
SELECT @NAME =
(SELECT 'C:\InsertTestdata.txt')
SET NOCOUNT ON;
SET @sqlCommand = 'BULK INSERT [dbo].[TableA] FROM ''' + @NAME + '''
WITH (DATAFILETYPE = ''char'',
FIELDTERMINATOR = '','',
ROWTERMINATOR = '''+CHAR(10)+''',
FIRSTROW = 2,
LASTROW = '''+ @LASTROW +'''
);'
EXEC (@sqlCommand);
我在执行上面的脚本时遇到错误 任何人都可以解释在Bulk Insert Statement中使用某个变量给Lastrow和firstrow参数的正确方法是什么?
答案 0 :(得分:1)
这样的事情:
DECLARE @sqlCommand VARCHAR(MAX) DECLARE @NAME varchar (100)
DECLARE @FIRSTROW INT,@LASTROW INT
SET @FIRSTROW = 4
--(SELECT TOP 1 [Id]
-- FROM [dbo].[TableB]
-- ORDER BY [Id] DESC) + 1
SET @LASTROW = @FIRSTROW + 4
SELECT @NAME =
(SELECT 'C:\InsertTestdata.txt')
SET NOCOUNT ON;
SET @sqlCommand = concat('BULK INSERT [dbo].[TableA] FROM ''' , @NAME , '''
WITH (DATAFILETYPE = ''char'',
FIELDTERMINATOR = '','',
ROWTERMINATOR = ''\n'',
FIRSTROW = 2,
LASTROW = ', @LASTROW ,'
);' );
print @sqlCommand;
输出
BULK INSERT [dbo].[TableA] FROM 'C:\InsertTestdata.txt'
WITH (DATAFILETYPE = 'char',
FIELDTERMINATOR = ',',
ROWTERMINATOR = '\n',
FIRSTROW = 2,
LASTROW = 8
);