if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[p_binaryIO]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[p_binaryIO]
GO
Create proc p_binaryIO
@servename varchar (30),--伺服器名稱
@username varchar (30), --使用者名
@password varchar (30), --密碼
@tbname varchar (500), --資料庫..表名
@fdname varchar (30), --字段名
@fname varchar (1000), --目錄+檔案名,處理過程中要使用/覆寫:@filename+_temp
@tj varchar (1000)='', --處理條件.對于資料導入,如果條件中包含@fdname,請指定表名字首
@isout bit=1 --1導出((預設),0導入
AS
declare @fname_in varchar(1000) --bcp處理應答檔案名
,@fsize varchar(20) --要處理的檔案的大小
,@m_tbname varchar(50) --臨時表名
,@sql varchar(8000)
--則取得導入檔案的大小
if @isout=1
set @fsize='0'
else
begin
create table #tb(可選名 varchar(20),大小 int
,建立日期 varchar(10),建立時間 varchar(20)
,上次寫操作日期 varchar(10),上次寫操作時間 varchar(20)
,上次通路日期 varchar(10),上次通路時間 varchar(20),特性 int)
insert into #tb
exec master..xp_getfiledetails @fname
select @fsize=大小 from #tb
drop table #tb
if @fsize is null
begin
print '檔案未找到'
return
end
end
--生成資料處理應答檔案
set @m_tbname='[##temp'+cast(newid() as varchar(40))+']'
set @sql='select * into '[email protected]_tbname+' from(
select null as 類型
union all select 0 as 字首
union all select '[email protected]+' as 長度
union all select null as 結束
union all select null as 格式
) a'
exec(@sql)
select @[email protected]+'_temp'
,@sql='bcp "'[email protected]_tbname+'" out "'[email protected]_in
+'" /S"'[email protected]
+case when isnull(@username,'')='' then ''
else '" /U"'[email protected] end
+'" /P"'+isnull(@password,'')+'" /c'
exec master..xp_cmdshell @sql
--删除臨時表
set @sql='drop table '[email protected]_tbname
exec(@sql)
if @isout=1
begin
set @sql='bcp "select top 1 '[email protected]+' from '
[email protected]+case isnull(@tj,'') when '' then ''
else ' where '[email protected] end
+'" queryout "'[email protected]
+'" /S"'[email protected]
+case when isnull(@username,'')='' then ''
else '" /U"'[email protected] end
+'" /P"'+isnull(@password,'')
+'" /i"'[email protected]_in+'"'
exec master..xp_cmdshell @sql
end
else
begin
--為資料導入準備臨時表
set @sql='select top 0 '[email protected]+' into '
[email protected]_tbname+' from ' [email protected]
exec(@sql)
--将資料導入到臨時表
set @sql='bcp "'[email protected]_tbname+'" in "'[email protected]
+'" /S"'[email protected]
+case when isnull(@username,'')='' then ''
else '" /U"'[email protected] end
+'" /P"'+isnull(@password,'')
+'" /i"'[email protected]_in+'"'
exec master..xp_cmdshell @sql
--将資料導入到正式表中
set @sql='update '[email protected]
+' set '[email protected]+'=b.'[email protected]
+' from '[email protected]+' a,'
[email protected]_tbname+' b'
+case isnull(@tj,'') when '' then ''
else ' where '[email protected] end
exec(@sql)
--删除資料處理臨時表
set @sql='drop table '[email protected]_tbname
end
--删除資料處理應答檔案
set @sql='del '[email protected]_in
exec master..xp_cmdshell @sql
go