Auto Import many .txt files into sql server table

拈花ヽ惹草 提交于 2020-01-17 10:28:29

问题


I have many .txt files and I want to import them into SQL Server table.

The file names are something like:

hazem.20160922.txt

hazem2.20160921.txt

The table exists already so no need to create it again. This is a daily activity, so I will need to automate that. I read many articles online and I am unable to do it.


回答1:


Since you said it is an automatic process that should happen every day, you can create an SSIS (ETL) Job to do this and you can schedule the job in such a away that it will run everyday.

Here is the link that will clearly explain how to create an ETL package as Flat File source and Database Destination.

This link will help you with step by step procedure for Scheduling a Job in SQL Server Agent.

You can select the folder path instead of file name in the Source so that ETL Job will move all the files in the folder to destination table once per day.




回答2:


using foreach loop in cursor

 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
      --bulk insert won`enter code here`'t take a variable name, so make a sql and execute it instead:
       set @sql = 'BULK INSERT Temp FROM ''' + @path + @filename + ''' '
           + '     WITH ( 
                   FIELDTERMINATOR = '','', 
                   ROWTERMINATOR = ''\n'', 
                   FIRSTROW = 2 
                ) '
print @sql
exec (@sql)

  fetch next from c1 into @path,@filename
  end
close c1
deallocate c1`enter code here`


来源:https://stackoverflow.com/questions/39640717/auto-import-many-txt-files-into-sql-server-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!