2017-09-25 176 views
0

我發現如此多的查詢聯機將多個文件導入到SQL Server中,從一個文件夾中導入到一個單獨的表中,但沒有幫助如何插入多個不同的文件作爲SQL Server中的不同表。我有21個文件(現在21個,可能會隨着時間而增加),並且從文件夾導入每個文件非常繁瑣。從文件夾中將多個不同的.txt文件導入到SQL Server

CREATE TABLE ALLFILENAMES(WHICHPATH VARCHAR(255),WHICHFILE varchar(255)) 

--some variables 
declare @filename varchar(255), 
     @path  varchar(255), 
     @sql  varchar(8000), 
     @cmd  varchar(1000) 


--get the list of files to process: 
SET @path = 'C:\Users\atp1lip\Desktop\09242017\' 
SET @cmd = 'dir ' + @path + '*.txt /b' 
INSERT INTO ALLFILENAMES(WHICHFILE) 
EXEC Master..xp_cmdShell @cmd 
UPDATE ALLFILENAMES SET WHICHPATH = @path where WHICHPATH is null 


--cursor loop 
declare c1 cursor for SELECT WHICHPATH,WHICHFILE FROM ALLFILENAMES where WHICHFILE like '%.txt%' 
open c1 
fetch next from c1 into @path,@filename 
While @@fetch_status <> -1 
    begin 

    set @sql = 'BULK INSERT test FROM ''' + @path + @filename + ''' ' 
     + '  WITH ( 
       FIELDTERMINATOR = '','', 
       ROWTERMINATOR = ''\n'' 
      ) ' 
print @sql 
exec (@sql) 

    fetch next from c1 into @path,@filename 
    end 
close c1 
deallocate c1 

我想知道是否有可能做到這一點?任何幫助表示讚賞。謝謝!

回答

0

,你也可以使用函數xp_dirtree這樣的:

CREATE TABLE #FilesList(ID INT IDENTITY(1,1), FileName VARCHAR(1000),Depth INT,isFile INT) 
    INSERT INTO #FilesList 
    EXEC xp_dirtree @FilePath, 1, 1 
相關問題