问题
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