【发布时间】:2014-09-29 08:59:26
【问题描述】:
我们有一个 Excel 文件文件夹,我们想使用 TSQL 将其导入到我们的数据库中。我们有使用OpenRowSet 导入单个文件的代码,但需要找到一种方法来遍历文件夹中的文件并在每个文件上运行此代码。这如何使用 TSQL 来完成?
【问题讨论】:
标签: sql-server-2008 tsql import
我们有一个 Excel 文件文件夹,我们想使用 TSQL 将其导入到我们的数据库中。我们有使用OpenRowSet 导入单个文件的代码,但需要找到一种方法来遍历文件夹中的文件并在每个文件上运行此代码。这如何使用 TSQL 来完成?
【问题讨论】:
标签: sql-server-2008 tsql import
做了一些研究,并找到了一种使用以下方法循环文件的方法:
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
【讨论】:
/s 添加到dir 命令,这样查询就独立于当前目录。
除了 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
【讨论】: