2014-09-29 95 views
4

我們有一個我們想要使用TSQL導入到數據庫中的excel文件的文件夾。我們有代碼使用OpenRowSet導入單個文件,但需要找到一種方法來遍歷文件夾中的文件並在每個文件上運行此代碼。如何使用TSQL完成這項工作?如何使用TSQL循環瀏覽文件夾中的所有文件?

回答

7

做了一些研究,並發現了一個地遍歷使用像這樣的文件:

CREATE TABLE #tmp(excelFileName VARCHAR(100)); 
INSERT INTO #tmp 
EXEC xp_cmdshell 'dir /B c:\my\folder\path\'; 

declare @fileName varchar(100) 

While (Select Count(*) From #tmp where excelFileName is not null) > 0 
Begin 

    Select Top 1 @fileName = excelFileName From #tmp 

    -- OPENROWSET processing goes here, using @fileName to identify which file to use 

    Delete from #tmp Where excelFileName = @FileName 

End 

DROP TABLE #tmp 
+0

加上'/ s'到'dir'命令,以便查詢獨立於當前目錄。 – Neo 2016-11-28 13:14:59

1

添加多到什麼Froadie說,你有可能需要先啓用使用shell命令(Enable 'xp_cmdshell' SQL Server)也是你CMD shell路徑可能需要有雙引號括起來,這是一個例子,我開始工作:

--Allow for SQL to use cmd shell 
EXEC sp_configure 'show advanced options', 1 -- To allow advanced options to be changed. 
RECONFIGURE -- To update the currently configured value for advanced options. 
EXEC sp_configure 'xp_cmdshell', 1 -- To enable the feature. 
RECONFIGURE -- To update the currently configured value for this feature. 

--Loop through all of the files 
CREATE TABLE #tmp(excelFileName VARCHAR(100)); 
INSERT INTO #tmp 
EXEC xp_cmdshell 'dir /B "C:\_GENERAL RESOURCES\CANWET\ANUSPLINE DATA CONVERTER\AnusplineStationSelector\CCDP\Files\"'; 

declare @fileName varchar(100) 

While (Select Count(*) From #tmp where excelFileName is not null) > 0 
Begin 

    Select Top 1 @fileName = excelFileName From #tmp 

    PRINT(@filename) 
    -- OPENROWSET processing goes here, using @fileName to identify which file to use 

    Delete from #tmp Where excelFileName = @FileName 

End 
相關問題