Sql server 2008 如何使用TSQL循环浏览文件夹中的所有文件?
我们有一个excel文件文件夹,希望使用TSQL将其导入数据库。我们有使用Sql server 2008 如何使用TSQL循环浏览文件夹中的所有文件?,sql-server-2008,tsql,import,Sql Server 2008,Tsql,Import,我们有一个excel文件文件夹,希望使用TSQL将其导入数据库。我们有使用OpenRowSet导入单个文件的代码,但需要找到一种方法循环遍历文件夹中的文件,并在每个文件上运行此代码。如何使用TSQL实现这一点?做了一些研究,并找到了一种使用如下内容循环文件的方法: CREATE TABLE #tmp(excelFileName VARCHAR(100)); INSERT INTO #tmp EXEC xp_cmdshell 'dir /B c:\my\folder\path\'; declar
OpenRowSet
导入单个文件的代码,但需要找到一种方法循环遍历文件夹中的文件,并在每个文件上运行此代码。如何使用TSQL实现这一点?做了一些研究,并找到了一种使用如下内容循环文件的方法:
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
除了Froadie所说的之外,您可能还需要首先启用命令shell()的使用。您的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
将
/s
添加到dir
命令中,使查询独立于当前目录。感谢使用此脚本。这真的帮了我很大的忙。干杯