2017-04-05 91 views
0

如果我執行下面的腳本,可以將數據插入到表中。無法從SQL中的平面文件批量插入

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. 

請幫助。提前致謝。

回答

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參考: