2016-03-28 93 views
1
DECLARE @SQL_BULK VARCHAR(MAX) 

SET @SQL_BULK = 'BULK INSERT [dbo].[Table] 
       FROM ''' + @BatchFileName + ''' 
       WITH 
       (
        FIRSTROW = 2, 
        FIELDTERMINATOR = ''\t'', 
        ROWTERMINATOR = ''0x0a'' 
       )' 

EXEC (@SQL_BULK) 

我有這段代碼來做批量加載。工作正常,但我想有@BatchFileName也在那裏作爲一列(每行包含相同的值)。SQL Server中批量加載時插入文件名

這是可能在批量加載過程中嗎?或者我以後如何在單獨的函數中添加它?

在此先感謝

回答

2

我使用這個腳本在目錄遍歷和bulkinsert文件:

create table #x (name varchar(200)) 
DECLARE @query varchar (1000),@conta int ,@query2 varchar (1000),@NOME varchar(50) 
set @conta=1 
set @query ='master.dbo.xp_cmdshell "dir '+'C:\directoryname'+'*.csv' +' /b"' 
insert #x exec (@query) 
delete from #x where name is NULL 
select identity(int,1,1) as ID, name into #y from #x 
drop table #x 
WHILE @conta<221 --number of files 

BEGIN 
SELECT @NOME=name FROM #y WHERE [email protected] 
set @Query2 ='BULK INSERT [dbo].[tablename] FROM '+ '''C:\directoryname'[email protected]+''' 
    WITH (
FIELDTERMINATOR = '','',ROWTERMINATOR = ''0x0a'')' 
SELECT @query2 
exec (@Query2) 

set @[email protected]+1 

END 
drop table #y