无法在SQL中从平面文件批量插入

时间:2017-04-05 21:06:33

标签: sql-server bulkinsert flat-file

如果我执行下面的脚本,可以将数据插入表中。

CREATE PROCEDURE dbo.loadDataFrFlatFile

AS
BEGIN


BULK INSERT PERSONS
FROM 'C:\SampleData1.csv'
WITH (FieldTerminator = '|', RowTerminator = '\n')
END

RETURN 1

GO

EXEC dbo.loadDataFrFlatFile

但是,如果我将文件路径作为输入变量,它就不起作用。

CREATE PROCEDURE dbo.loadDataFrFlatFile
(
    @flatFilePath varchar(255)
)

AS
BEGIN    

BULK INSERT PERSONS
FROM ' + @flatFilePath + '
WITH (FieldTerminator = '|', RowTerminator = '\n')
END

RETURN 1

GO

EXEC dbo.loadDataFrFlatFile @flatFilePath = 'C:\SampleData1.csv'

显示的错误是:

Msg 4860, Level 16, State 1, Procedure loadDataFrFlatFile, Line 12
Cannot bulk load. The file " + @flatFilePath + " does not exist.

请帮忙。提前谢谢。

2 个答案:

答案 0 :(得分:1)

您需要使用动态sql,例如:

create procedure dbo.loadDataFrFlatFile ( @flatFilePath varchar(255) ) as
begin;
declare @sql nvarchar(max) = 'bulk insert persons
from ''' + @flatFilePath + '''
with (FieldTerminator = ''|'', RowTerminator = ''\n'')
';
exec sp_executesql @sql;
return 1
end;
go

exec dbo.loadDataFrFlatFile @flatFilePath = 'C:\SampleData1.csv'

关于sql注入要小心,确保只有那些需要使用它的人才有权执行它。

您还可以在连接和执行变量之前对变量可以包含的值进行白名单和黑名单。

动态sql参考:

答案 1 :(得分:0)

来自https://docs.microsoft.com/en-us/sql/t-sql/statements/bulk-insert-transact-sql

尝试类似

的内容
DECLARE @bulk_cmd varchar(1000);  
SET @bulk_cmd = 'BULK INSERT AdventureWorks2012.Sales.SalesOrderDetail  
FROM ''<drive>:\<path>\<filename>''   
WITH (ROWTERMINATOR = '''+CHAR(10)+''')';  
EXEC(@bulk_cmd);