用BCP批量将文本文件导入表中

用BCP批量将文本文件导入表中

--王成辉原创,转贴请注明出自微软BI开拓者www.windbi.com

set nocount on
declare @sql varchar(500),@id1 int,@id2 int
create table #T (id int identity(1,1),col varchar(500))
insert into #T exec master..xp_cmdshell 'dir C:\*.txt'
delete from #T where col not like '%.txt%' or col is null
update #T set col=replace(col,left(col,36),'')--这里36做适当的修改
select @id1=min(id),@id2=max(id) from #T
while @id1<
=@id2
begin
select @sql='bcp DBName..TableName in "C:\'+col+'" -fc:\1.fmt -Sservername -Usa -Ppassword'
from #T where
id=@id1
--select @sql='bcp DBName..TableName in "C:\'+col+'" -c -Sservername -Usa -Ppassword'
--from #T where
id=@id1
print @sql
set @id1=@id1+1
exec master..xp_cmdshell @sql
end
drop table #T

虽有智慧,不如乘势;虽有鎡基,不如待时。
君子学以聚之,问以辨之,宽以居之,仁以行之。
独学而无友,则孤陋而寡闻。