There are several ways to do this. First, you can use an anonymous block with a nested statement table or an associative array of statements. A nested table approach requires a slightly smaller change to an existing script, but there is a risk that the numbers will fail. Note that I am using an alternative citation mechanism, for example. q '[character] ... [character]', in case your DDL contains some apostrophes.
This code is similar to some other answers, but with Oracle syntax and does not require the creation of additional objects.
Nested table script:
--Only create the tables between the two values (nested table) declare type varchar_tab is table of varchar2(32767); table_statements varchar_tab := varchar_tab( q'!create table tab1 (test1 number)!', q'!create table tab2 (test1 number)!', q'!create table tab3 (test1 number)!', q'!create table tab4 (test1 number)!' ); begin for i in &1 .. &2 loop execute immediate table_statements(i); end loop; end; /
Associative array script:
--Only create the tables between the two values (associative array) declare type varchar_tab is table of varchar2(32767) index by number; table_statements varchar_tab; begin table_statements(1) := q'!create table tab1 (test1 number)!'; table_statements(2) := q'!create table tab2 (test1 number)!'; table_statements(3) := q'!create table tab3 (test1 number)!'; table_statements(4) := q'!create table tab4 (test1 number)!'; --Only create the tables between the two values for i in &1 .. &2 loop execute immediate table_statements(i); end loop; end; /
If you want your script to be almost identical to its current form, another approach would be to run the entire script and then add an anonymous block at the end that removes unnecessary tables. This keeps the top of your script very simple, but obviously there may be some problems with automatically dropping tables.
--Drop all the tables except for those within the range declare table_does_not_exist exception; pragma exception_init(table_does_not_exist, -00942); begin for i in 1 .. 1000 loop if i between &1 and &2 then null; else begin execute immediate 'drop table tab'||i; exception when table_does_not_exist then null; end; end if; end loop; end; /
source share