if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[p_export]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[p_export]
GO/*--导出表中的image列为文件 导出当前库,指定表中,指定的image/text/ntext列的数据为文件
导出生成的文件以表中的主键做为文件名
可以在指定导出目录时,指定文件的前缀
导出处理采用了windows身份验证,如果你的sql不支持windows身份验证
则需要把bcp处理语句中的 /T,替换为 /U"sa" /P"sa的密码"--邹建 2005.04(引用请保留此信息)--*//*--调用示例 --导出图像
exec p_export 'pub_info','pub_id','logo' --导出文本文件,文件名以pp开头
exec p_export 'pub_info','pub_id','pr_info','c:\pp_','.txt'
--*/
create proc p_export
@tbname sysname,  --要进行导出处理的表名
@keyfd  sysname,  --要进行导出处理的主键名
@imgfd  sysname,  --要导出的图像字段名
@path nvarchar(1000)='c:\', --导出的图像文件要保存的目录
@file sysname='',           --导出的图像文件扩展名,默认为.gif
                            --如果是.开头,表明是直接指定的扩展名
                            --否则表示从表中的该字段获取扩展名
@whereand nvarchar(1000)='' --导出数据的条件
as
declare @fmtfile nvarchar(1000),@s nvarchar(4000)
if isnull(@path,'')='' set @path='c:\'if isnull(@file,'')='' set @file='.gif'select top 1 @fmtfile=rtrim(reverse(filename)) 
from master.dbo.sysfiles where name=N'master'
select @fmtfile=stuff(@fmtfile,1,charindex('\',@fmtfile),N'')
,@fmtfile=reverse(stuff(@fmtfile,1,charindex('\',@fmtfile),N''))
+N'\BACKUP\'+cast(newid() as nvarchar(36))+N'.fmt'
set @s=N'bcp "select null union all select 0 union all select 0 union all select null union all select null"'
+N' queryout "'+@fmtfile+N'" /T /c'
exec master..xp_cmdshell @s,no_outputset @s=N'
declare tb cursor local
for
select N''bcp "select ''+quotename(@imgfd)
+'' from ''+quotename(db_name())
+''..''+quotename(@tbname)
+'' where ''+quotename(@keyfd)
+''=''+rtrim(pub_id)
+''" queryout "''+@path+rtrim(pub_id)+'
+case when left(@file,1)='.' then quotename(@file,'''')
else N'ltrim('+quotename(@file)+N')' end+N'
+''" /T /i"''+@fmtfile+''"''
from '+quotename(@tbname)
+case when isnull(@whereand,'')='' then ''
else  N' where '+@whereand end
+N'
open tb
fetch tb into @s
while @@fetch_status=0
begin
exec master..xp_cmdshell @s--,no_output
fetch tb into @s
end
close tb
deallocate tb'
exec sp_executesql @s,N'
@tbname sysname,
@keyfd  sysname,
@imgfd  sysname,
@path nvarchar(1000),
@file nvarchar(10),
@fmtfile nvarchar(1000),
@s nvarchar(4000)',
@tbname,@keyfd,@imgfd,@path,@file,@fmtfile,@s
set @s='del "'+@fmtfile+N'"'
exec master..xp_cmdshell @s,no_output
go