如何使用TSQL遍历文件夹中的所有文件?

fro*_*die 6 t-sql import sql-server-2008

我们有一个excel文件的文件夹,我们想要使用TSQL导入我们的数据库.我们有使用代码导入单个文件OpenRowSet,但需要找到一种方法来遍历文件夹中的文件并在每个文件上运行此代码.如何使用TSQL实现这一目标?

fro*_*die 10

做了一些研究,并找到了一种使用以下方法循环文件的方法:

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
Run Code Online (Sandbox Code Playgroud)


小智 5

添加更多 Froadie 所说的内容,您可能需要首先启用命令外壳的使用(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
Run Code Online (Sandbox Code Playgroud)