首先声明,这个存储过程大部分是SQL77写出来的,哥这几天正研究快照隔离下OPENXML语句JOIN以后报错的问题,头大ING。。。
还好有屁7帮了我这个忙,不然累死。
思路非常简单,XP_CMDSHELL读取某一目录下的文件名称,然后游标遍历之,代码就在下面了
IF OBJECT_ID('P_EXCELFILETODATA') IS NOT NULL DROP PROC P_EXCELFILETODATA GO CREATE PROC P_EXCELFILETODATA ( @PATH SYSNAME, --完全路径名 @FILTER SYSNAME='*.XLSX',--默认导EXCEL2007的 @TBNAME VARCHAR(MAX) --插入的表名 ) AS --@PATH 完全路径名(D:\XXXX\) --@FILTER 筛选的文件名选项以及文件类型(合并一起输入) SET NOCOUNT ON DECLARE @S NVARCHAR(4000),@SQL NVARCHAR(4000)--,@PATH NVARCHAR(4000),@FILTER SYSNAME SET @S='DIR '+@PATH+@FILTER+'/B' CREATE TABLE #FILE(FLNAME SYSNAME NULL) INSERT INTO #FILE EXEC MASTER..XP_CMDSHELL @S DECLARE @FILE SYSNAME,@SHEETNAME SYSNAME DECLARE CUR_FILENAME CURSOR FOR SELECT * FROM #FILE WHERE [FLNAME] IS NOT NULL AND [FLNAME]<>'找不到文件' OPEN CUR_FILENAME FETCH NEXT FROM CUR_FILENAME INTO @FILE WHILE @@FETCH_STATUS=0 BEGIN SET @SHEETNAME=LEFT(@FILE,CHARINDEX('.',@FILE)-1) --PRINT @SHEETNAME SELECT @SQL = ISNULL(@SQL,'')+ 'INSERT INTO ' + @TBNAME + ' SELECT * FROM OPENROWSET( ''MICROSOFT.ACE.OLEDB.12.0'', ''EXCEL 12.0;HDR=YES;IMEX=1;DATABASE='+@PATH+@FILE+''',''SELECT * FROM ['+@SHEETNAME+'$]'')' FETCH NEXT FROM CUR_FILENAME INTO @FILE END EXEC(@SQL) CLOSE CUR_FILENAME DEALLOCATE CUR_FILENAME GO --测试 --在D盘建立ExcelFiles文件夹,里面建立3个EXCEL文档,分别命名为a,b,c --记得把三个EXCEL的SHEET1改成a,b,c IF OBJECT_ID('TB')IS NOT NULL DROP TABLE TB GO CREATE TABLE TB ( A VARCHAR(10), B VARCHAR(10), C VARCHAR(10), D VARCHAR(10) ) GO EXEC P_EXCELFILETODATA 'D:\ExcelFiles\','*.XLSX','TB' GO SELECT * FROM TB /*A B C D ---------- ---------- ---------- ---------- 1 2 3 4 2 3 4 5 2 3 s s w w w w (4 行受影响)*/