我们有一个excel文件夹,我们想用TSQL将它们导入我们的数据库。我们有使用OpenRowSet
导入单个文件的代码,但是需要找到一种方法来遍历文件夹中的文件并在每个文件上运行此代码。如何使用TSQL实现这一目标?
答案 0 :(得分: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
答案 1 :(得分:2)
为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