批量执行动态SQL语句

清华大佬耗费三个月吐血整理的几百G的资源,免费分享!....>>>

-- exesql_batch
declare
	-- incomming param
	v_oriSql VARCHAR2(1024):= 'create table TABLE_[N]_[D] as select * from TABLE where 1=2';	-- original sql
	v_beg  NUMBER := 0;  -- begin of number
	v_end NUMBER := 9; -- end of number [beg, end]
	v_begDate DATE := to_date('20130701', 'YYYYMMDD');	-- begin date
	v_endDate DATE := to_date('20130731', 'YYYYMMDD');	-- end date, [beg, end]
	v_dateSw NUMBER := 1; -- date switch 1:day, others:month
	-- internel var
	v_dateNum NUMBER := 0;
	v_numNum NUMBER := 0;
	v_strDate VARCHAR2(8);
	v_destSql VARCHAR2(2000);
	V_DATE VARCHAR2(3) := '[D]';
	V_NUM VARCHAR2(3) := '[N]';
begin
	if INSTR(v_oriSql, V_DATE) <> 0 then
		if v_dateSw = 1 then
			v_dateNum := trunc(v_endDate, 'DD') - trunc(v_begDate, 'DD');
		else
			v_dateNum := MONTHS_BETWEEN(trunc(v_endDate, 'MM'), trunc(v_begDate, 'MM'));
		end if;
	end if;
	
	if INSTR(v_oriSql, V_NUM) <> 0 then
		v_numNum := v_end - v_beg;
	end if;
	
	-- loop
	for i in 0 .. v_numNum loop
		for j in 0 .. v_dateNum loop
			if v_dateSw = 1 then
				v_strDate := to_char(v_begDate + j, 'YYYYMMDD');
			else
				v_strDate := to_char(ADD_MONTHS(v_begDate, j), 'YYYYMM');
			end if;
			v_destSql := REPLACE(v_oriSql, V_NUM, v_beg + i);
			v_destSql := REPLACE(v_destSql, V_DATE, v_strDate);
			EXECUTE IMMEDIATE v_destSql;
		end loop;
	end loop;
end;