if exists(select * from sysobjects where type=‘p‘ and name=‘sp_export_posm_data‘) begin
drop procedure sp_export_posm_data;
end;
go
create procedure sp_export_posm_data
@file_path varchar(200) /*导出后文件存放的路径*/
as
declare @exec_sql varchar(1000);
declare @file_name varchar(200); /*文件名称,时间格式,主要是用于记录数据是什么时候导出备份的*/
declare @table_name varchar(100); /*要导出数据的表名*/
declare @sql varchar(1000); /*执行业务数据查询的sql语句*/
/*要备份数据的业务表名*/
declare cur_tables cursor for
select name from sysobjects where 1=1 and type=‘u‘
and name like ‘WM_ORDER%‘ or name like ‘WM_PICKING%‘ or name like ‘RP_%‘
begin try
open cur_tables;
fetch next from cur_tables into @table_name;
while @@FETCH_STATUS = 0 begin
set @file_name = ‘‘;
set @file_path = ‘‘;
set @sql = ‘select * from DHL_POSM_WS..‘+@table_name;
set @sql += ‘ where 1=1 and DATEDIFF(MONTH,MODIFY_TIME,GETDATE())>10‘;
print @sql;
set @exec_sql = ‘ bcp "‘+@sql+‘" queryout ‘;
if ‘‘=@file_path begin
set @file_path = ‘D:\Program Files (x86)\Microsoft SQL Server\‘;
end;
print ‘111111‘;
set @file_name = @table_name+‘_‘+CONVERT(varchar(100), GETDATE(), 112)+‘.xls‘;
set @file_path = @file_path + @file_name; /*文件路径*/
print ‘2222222‘;
set @exec_sql = @exec_sql +‘"‘+@file_path+‘"‘;
set @exec_sql = @exec_sql +‘ -c -S"127.0.0.1\SQLEXPRESS" -U"DHL_POSM_WS" -P"DHLposm"‘;
print @exec_sql;
-- 导出数据到本地文件
exec master..xp_cmdshell @exec_sql;
fetch next from cur_tables into @table_name;
end;
close cur_tables; -- 关闭游标
deallocate cur_tables;-- 释放游标
end try
begin catch
close cur_tables; -- 关闭游标
deallocate cur_tables;-- 释放游标
end catch;
go