/*--原帖地址:
http://community.csdn.net/Expert/topic/3851/3851741.xml?temp=.4726831
--*/
--測試數據
create table tb(id varchar(50) primary key,detail text)
insert tb select 'aaa','11111'
union all select 'bbb','43424'
union all select 'clearcase/" target="_blank" >ccc','324234'
/*--處理要求
把上述表中的detail字段導出為文本文件,要求每條記錄一個文件,文件名為id+.txt
即上述表中的數據要求導出為 aaa.txt,bbb.txt,ccc.txt
--*/
go
--處理的存儲過程
create proc p_export
@path nvarchar(1000) --導出的文本文件保存的目錄
as
declare @s nvarchar(4000)
if isnull(@path,'')='' set @path='c:\'
else if right(@path,1)<>'\' set @path=@path+'\'
--用游標構建每條記錄的bcp導出語句,BCP的語法參考sql聯機幫助
declare tb cursor local
for
select 'BCP "select detail from '
+quotename(db_name())
+'..tb where id='
+quotename(id,N'''')
+'" queryout "'+@path
+id+'.txt" /T /w'
from tb
open tb
fetch tb into @s
while @@fetch_status=0
begin
--調用xp_cmdshell存儲過程執行bcp進行導出處理
exec master..xp_cmdshell @s,no_output
fetch tb into @s
end
close tb
deallocate tb
go
--調用
exec p_export 'c:\'
go
--刪除測試
drop table tb
drop proc p_export