从文件夹

时间:2017-09-25 18:39:16

标签: sql-server bulkinsert

我在网上发现了很多查询,将多个文件导入SQL Server,从一个文件夹中导入一个表,如下所示,但没有在线帮助如何在SQL Server中将多个不同的文件作为不同的表插入。我有21个文件(现在21个,可能会随着时间的推移而增加),从文件夹中导入每个文件真的非常繁琐。

CREATE TABLE ALLFILENAMES(WHICHPATH VARCHAR(255),WHICHFILE varchar(255))

--some variables
declare @filename varchar(255),
        @path     varchar(255),
        @sql      varchar(8000),
        @cmd      varchar(1000)


--get the list of files to process:
SET @path = 'C:\Users\atp1lip\Desktop\09242017\'
SET @cmd = 'dir ' + @path + '*.txt /b'
INSERT INTO  ALLFILENAMES(WHICHFILE)
EXEC Master..xp_cmdShell @cmd
UPDATE ALLFILENAMES SET WHICHPATH = @path where WHICHPATH is null


--cursor loop
declare c1 cursor for SELECT WHICHPATH,WHICHFILE FROM ALLFILENAMES where WHICHFILE like '%.txt%'
open c1
fetch next from c1 into @path,@filename
While @@fetch_status <> -1
  begin

   set @sql = 'BULK INSERT test FROM ''' + @path + @filename + ''' '
       + '     WITH ( 
               FIELDTERMINATOR = '','', 
               ROWTERMINATOR = ''\n''
            ) '
print @sql
exec (@sql)

  fetch next from c1 into @path,@filename
  end
close c1
deallocate c1

我想知道它是否可以这样做?任何帮助表示赞赏。谢谢!

1 个答案:

答案 0 :(得分:0)

你也可以像这样使用函数xp_dirtree:

def draw_a_line_of_plus(length):

 for i in range (length):
    print ('+', end='')