我试图每天将.txt文件导入到sql server 2008表中,我想自动化它
所以步骤:
1-我每天收到2个文件,名称为hazem.log.date和hazem.log.date2
2-我需要有一种方法每天自动导入它们
3-我将使用该作业,但在这种情况下应该使用哪个命令或查询?
答案 0 :(得分:1)
尝试通过SQLServer作业运行以下..
BULK INSERT dbo.ImportTest
FROM 'C:\ImportData.txt' --replace name of your files
WITH ( FIELDTERMINATOR =',', FIRSTROW = 2 )
您也可以使用
bcp dbo.ImportTest in 'C:\ImportData.txt' -T -SserverName\instanceName
对于多个文件..你可以这样做..
1.首先创建存储过程..
Create procedure usp_ImportMultipleFilesBCP @servername varchar(128),
@DatabaseName varchar(128), @filepath varchar(500), @pattern varchar(100),
@TableName varchar(128)
as
declare @query varchar(1000)
declare @max1 int
declare @count1 int
Declare @filename varchar(100)
set @count1 =0
create table #x (name varchar(200))
set @query ='master.dbo.xp_cmdshell "dir '+@filepath+@pattern +' /b"'
insert #x exec (@query)
delete from #x where name is NULL
select identity(int,1,1) as ID, name into #y from #x
drop table #x
set @max1 = (select max(ID) from #y)
--print @max1
--print @count1
--select * from #y
While @count1 <= @max1
begin
set @count1=@count1+1
set @filename = (select name from #y where [id] = @count1)
set @Query ='bcp "'+ @databasename+'.dbo.'+@Tablename + '"
in "'+ @Filepath+@Filename+'" -S' + @servername + ' -T -c -r\n -t,'
set @Query = 'MASTER.DBO.xp_cmdshell '+ "'"+ @query +"'"
--print @query
EXEC ( @query)
insert into logtable (query) select @query
end
2.现在在sp上面运行以导入所需扩展名的所有文件
Exec usp_ImportMultipleFilesBCP 'SQL','Bank','c:\Myimport\','*.csv','Account'--table account
注意:
您需要启用Xp_cmdshell
参考文献:
https://www.mssqltips.com/sqlservertip/1207/different-options-for-importing-data-into-sql-server/
http://www.databasejournal.com/features/mssql/article.php/3325701/Import-multiple-Files-to-SQL-Server-using-T-SQL.htm