154.(BCP)导出表中的image列为文件

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的密码"

/*--调用示例

	--导出图像
	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_output

set @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
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值