Generate create table DDL from View - sql

I have a read access only oracle db that exposes Views for me to consume and I want to have local db where I insert the above data. To do that I need to generate create table DDL based on a views and I've found no way to do this.
To clarify I've used
SELECT dbms_metadata.get_ddl('VIEW','table','schema') FROM dual
The result of that statement is
CREATE OR REPLACE VIEW "SCHEMA"."VIEW_NAME" ("ID","NAME") AS
SELECT * FROM SQUARE S
JOIN SHAPE SH ON( S.ID==SH.ID)
where what I want to generate is
CREATE TABLE table_name (
ID NUMBER,
NAME VARCHER2(100),
Also I can't just run
CREATE TABLE new_table
AS (SELECT * FROM view WHERE 1=2);
As the db I can read I can't create tables in.
Is there any tool that allows to run this with 2 db connections ? would that work?
EDIT: For those that can't figure how to do the database Link here is a garbage throwaway script that worked for me
DECLARE
starting boolean := TRUE;
r_owner varchar2(30) := '$1';
r_table_name varchar2(30) := '';
BEGIN
FOR v IN ( --views from a owner
SELECT
VIEW_NAME
FROM
all_views
WHERE owner = r_owner)
LOOP
r_table_name:= v.view_name;
dbms_output.put_line('create table ' || r_owner || '.' || r_table_name || '(');
starting := TRUE;
FOR r IN ( -- columns from table
SELECT
column_name,
data_type,
data_length,
data_precision,
nullable
FROM
all_tab_columns
WHERE
table_name = upper(r_table_name)
AND owner = upper(r_owner)
ORDER BY column_id)
LOOP
IF starting THEN
starting := FALSE;
ELSE
dbms_output.put_line(',');
END IF;
IF r.data_type = 'NUMBER' THEN
IF r.data_length = 22 THEN
dbms_output.put(' '|| r.column_name || ' NUMBER');
ELSE
dbms_output.put(' '|| r.column_name || ' NUMBER(' || r.data_length || ')');
END IF;
ELSIF r.data_type = 'FLOAT' THEN
dbms_output.put(' '|| r.column_name || ' FLOAT(' || r.data_precision || ')');
ELSIF instr(r.data_type, 'CHAR') >0 then
dbms_output.put(' '|| r.column_name||' '||r.data_type||'('||r.data_length||')');
ELSE
dbms_output.put(' '|| r.column_name || ' ' || r.data_type);
END IF;
IF r.nullable = 'N' THEN
dbms_output.put(' NOT NULL');
END IF;
END LOOP;
dbms_output.put_line('');
dbms_output.put_line(' ); ');
dbms_output.put_line('');
END LOOP;
END;

In your local db, create a link to the 'read only' db:
CREATE DATABASE LINK READONLY_DB
CONNECT TO scott IDENTIFIED BY tiger
USING 'readonlydb';
Note, the USING 'readonbly' is referencing a tnsnames.ora entry for your readonly database. Substitute 'readonlydb' with the appropriate, correct value.
Then, with the db link created:
create table my_table as select * from readonly_table#readonly_db;
Where:
'readonly_table' represents the name of the table at the readonly database
'readonly_db' is the name of the database link you created in the first step.

Related

ORA-04091 TABLE ODB.EMPLOYEE IS MUTATING, TRIGGER/FUNCTION MAY NOT SEE IT. IS THERE SOMETHING WRONG WITH MY TRIGGER?

Trying to create a trigger when there is an update of Status on Employee Table and capture some values for the record in Employee table and Employee_Header table for that record and send an email. The trigger throws an error.
CREATE OR REPLACE TRIGGER ODB.TRG_EMPLOYEE_STATUS_EMAIL
AFTER UPDATE OF STATUS ON ODB.EMPLOYEE
FOR EACH ROW
DECLARE
s_message varchar2(4000);
s_subject varchar2(1000);
s_return_message varchar2(4000);
s_database varchar2(50);
v_rm EMPLOYEE%ROWTYPE;
v_sh EMPLOYEE_HEADER%ROWTYPE;
BEGIN
if :old."STATUS" = 'HOLD' AND :new."STATUS" = 'ACTIVE' AND :new."CATEGORY" = 'FULLTIME' then
select * into v_rm from EMPLOYEE WHERE :new."STATUS" = 'ACTIVE' AND ROWNUM>1;
select * into v_sh from EMPLOYEE_HEADER WHERE ROWNUM>1;
s_subject := 'NAME ' || v_rm.NAME ||' message ' || ' CHECK LOG OF EMPLOYEE' || Chr(13) || ' STATUS: ' || v_rm.STATUS ;
s_message := 'SAMPLE' || Chr(10)||Chr(13) || 'THE STATUS IN EMPLOYEE_HEADER IS: ' || Chr(10)|| ' STATUS: ' || v_sh.STATUS ;
pkg_email.sendEmail('INPUT PARAMETERS TO SEND EMAIL');
end if;
END;
You can't select from a table which is just being changed; it is mutating. Though, as you can use the :new pseudorecord, you can "skip" that error. Also, where rownum > 1 is useless as it is never true. I don't know what you meant to say by using it.
I see you've created columns using double quotes. In Oracle, that's usually a mistake. Not that it won't work - it will, but you always have to reference columns using double quotes and match letter case.
Finally, trigger might look like this (read comments within code):
create or replace trigger odb.trg_employee_status_email
after update of status on odb.employee
for each row
declare
s_message varchar2(4000);
s_subject varchar2(1000);
s_return_message varchar2(4000);
s_database varchar2(50);
-- v_rm employee%rowtype; -- you don't need that
v_sh employee_header%rowtype;
begin
if :old."status" = 'HOLD' and :new."status" = 'ACTIVE' and
:new."category" = 'FULLTIME'
then
-- You can't select from a table which is just being changed - it is "mutating".
-- Besides, AND ROWNUM > 1 will never return anything. You can only check
-- ROWNUM <= some_value
--select * into v_rm from employee where :new."status" = 'ACTIVE' and rownum>1;
select * into v_sh from employee_header where rownum>1;
-- instead of SELECT ... INTO V_RM, use :NEW pseudorecord
s_subject := 'NAME ' || :new.name ||' message ' || ' CHECK LOG OF EMPLOYEE'
|| chr(13) || ' STATUS: ' || :new.status ;
s_message := 'SAMPLE' || chr(10)||chr(13) || 'THE STATUS IN EMPLOYEE_HEADER IS: ' || chr(10)|| ' STATUS: ' || v_sh.status ;
pkg_email.sendemail('INPUT PARAMETERS TO SEND EMAIL');
end if;
exception
when no_data_found then null;
end;

Adding a new column at certain place in Postgres [duplicate]

How to add a new column in a table after the 2nd or 3rd column in the table using postgres?
My code looks as follows
ALTER TABLE n_domains ADD COLUMN contract_nr int after owner_id
No, there's no direct way to do that. And there's a reason for it - every query should list all the fields it needs in whatever order (and format etc) it needs them, thus making the order of the columns in one table insignificant.
If you really need to do that I can think of one workaround:
dump and save the description of the table in question (using pg_dump --schema-only --table=<schema.table> ...)
add the column you want where you want it in the saved definition
rename the table in the saved definition so not to clash with the name of the old table when you attempt to create it
create the new table using this definition
populate the new table with the data from the old table using 'INSERT INTO <new_table> SELECT field1, field2, <default_for_new_field>, field3,... FROM <old_table>';
rename the old table
rename the new table to the original name
eventually drop the old, renamed table after you make sure everything's alright
The order of columns is not irrelevant, putting fixed width columns at the front of the table can optimize the storage layout of your data, it can also make working with your data easier outside of your application code.
PostgreSQL does not support altering the column ordering (see Alter column position on the PostgreSQL wiki); if the table is relatively isolated, your best bet is to recreate the table:
CREATE TABLE foobar_new ( ... );
INSERT INTO foobar_new SELECT ... FROM foobar;
DROP TABLE foobar CASCADE;
ALTER TABLE foobar_new RENAME TO foobar;
If you have a lot of views or constraints defined against the table, you can re-add all the columns after the new column and drop the original columns (see the PostgreSQL wiki for an example).
The real problem here is that it's not done yet. Currently PostgreSQL's logical ordering is the same as the physical ordering. That's problematic because you can't get a different logical ordering, but it's even worse because the table isn't physically packed automatically, so by moving columns you can get different performance characteristics.
Arguing that it's that way by intent in design is pointless. It's somewhat likely to change at some point when an acceptable patch is submitted.
All of that said, is it a good idea to rely on the ordinal positioning of columns, logical or physical? Hell no. In production code you should never be using an implicit ordering or *. Why make the code more brittle than it needs to be? Correctness should always be a higher priority than saving a few keystrokes.
As a work around, you can in fact modify the column ordering by recreating the table, or through the "add and reorder" game
See also,
Column tetris reordering in order to make things more space-efficient
The column order is relevant to me, so I created this function. See if it helps. It works with indexes, primary key, and triggers. Missing Views and Foreign Key and other features are missing.
Example:
SELECT xaddcolumn('table', 'col3 int NOT NULL DEFAULT 0', 'col2');
Source code:
CREATE OR REPLACE FUNCTION xaddcolumn(ptable text, pcol text, pafter text) RETURNS void AS $BODY$
DECLARE
rcol RECORD;
rkey RECORD;
ridx RECORD;
rtgr RECORD;
vsql text;
vkey text;
vidx text;
cidx text;
vtgr text;
ctgr text;
etgr text;
vseq text;
vtype text;
vcols text;
BEGIN
EXECUTE 'CREATE TABLE zzz_' || ptable || ' AS SELECT * FROM ' || ptable;
--colunas
vseq = '';
vcols = '';
vsql = 'CREATE TABLE ' || ptable || '(';
FOR rcol IN SELECT column_name as col, udt_name as coltype, column_default as coldef,
is_nullable as is_null, character_maximum_length as len,
numeric_precision as num_prec, numeric_scale as num_scale
FROM information_schema.columns
WHERE table_name = ptable
ORDER BY ordinal_position
LOOP
vtype = rcol.coltype;
IF (substr(rcol.coldef,1,7) = 'nextval') THEN
vtype = 'serial';
vseq = vseq || 'SELECT setval(''' || ptable || '_' || rcol.col || '_seq'''
|| ', max(' || rcol.col || ')) FROM ' || ptable || ';';
ELSIF (vtype = 'bpchar') THEN
vtype = 'char';
END IF;
vsql = vsql || E'\n' || rcol.col || ' ' || vtype;
IF (vtype in ('varchar', 'char')) THEN
vsql = vsql || '(' || rcol.len || ')';
ELSIF (vtype = 'numeric') THEN
vsql = vsql || '(' || rcol.num_prec || ',' || rcol.num_scale || ')';
END IF;
IF (rcol.is_null = 'NO') THEN
vsql = vsql || ' NOT NULL';
END IF;
IF (rcol.coldef <> '' AND vtype <> 'serial') THEN
vsql = vsql || ' DEFAULT ' || rcol.coldef;
END IF;
vsql = vsql || E',';
vcols = vcols || rcol.col || ',';
--
IF (rcol.col = pafter) THEN
vsql = vsql || E'\n' || pcol || ',';
END IF;
END LOOP;
vcols = substr(vcols,1,length(vcols)-1);
--keys
vkey = '';
FOR rkey IN SELECT constraint_name as name, column_name as col
FROM information_schema.key_column_usage
WHERE table_name = ptable
LOOP
IF (vkey = '') THEN
vkey = E'\nCONSTRAINT ' || rkey.name || ' PRIMARY KEY (';
END IF;
vkey = vkey || rkey.col || ',';
END LOOP;
IF (vkey <> '') THEN
vsql = vsql || substr(vkey,1,length(vkey)-1) || ') ';
END IF;
vsql = substr(vsql,1,length(vsql)-1) || ') WITHOUT OIDS';
--index
vidx = '';
cidx = '';
FOR ridx IN SELECT s.indexrelname as nome, a.attname as col
FROM pg_index i LEFT JOIN pg_class c ON c.oid = i.indrelid
LEFT JOIN pg_attribute a ON a.attrelid = c.oid AND a.attnum = ANY(i.indkey)
LEFT JOIN pg_stat_user_indexes s USING (indexrelid)
WHERE c.relname = ptable AND i.indisunique != 't' AND i.indisprimary != 't'
ORDER BY s.indexrelname
LOOP
IF (ridx.nome <> cidx) THEN
IF (vidx <> '') THEN
vidx = substr(vidx,1,length(vidx)-1) || ');';
END IF;
cidx = ridx.nome;
vidx = vidx || E'\nCREATE INDEX ' || cidx || ' ON ' || ptable || ' (';
END IF;
vidx = vidx || ridx.col || ',';
END LOOP;
IF (vidx <> '') THEN
vidx = substr(vidx,1,length(vidx)-1) || ')';
END IF;
--trigger
vtgr = '';
ctgr = '';
etgr = '';
FOR rtgr IN SELECT trigger_name as nome, event_manipulation as eve,
action_statement as act, condition_timing as cond
FROM information_schema.triggers
WHERE event_object_table = ptable
LOOP
IF (rtgr.nome <> ctgr) THEN
IF (vtgr <> '') THEN
vtgr = replace(vtgr, '_#eve_', substr(etgr,1,length(etgr)-3));
END IF;
etgr = '';
ctgr = rtgr.nome;
vtgr = vtgr || 'CREATE TRIGGER ' || ctgr || ' ' || rtgr.cond || ' _#eve_ '
|| 'ON ' || ptable || ' FOR EACH ROW ' || rtgr.act || ';';
END IF;
etgr = etgr || rtgr.eve || ' OR ';
END LOOP;
IF (vtgr <> '') THEN
vtgr = replace(vtgr, '_#eve_', substr(etgr,1,length(etgr)-3));
END IF;
--exclui velha e cria nova
EXECUTE 'DROP TABLE ' || ptable;
IF (EXISTS (SELECT sequence_name FROM information_schema.sequences
WHERE sequence_name = ptable||'_id_seq'))
THEN
EXECUTE 'DROP SEQUENCE '||ptable||'_id_seq';
END IF;
EXECUTE vsql;
--dados na nova
EXECUTE 'INSERT INTO ' || ptable || '(' || vcols || ')' ||
E'\nSELECT ' || vcols || ' FROM zzz_' || ptable;
EXECUTE vseq;
EXECUTE vidx;
EXECUTE vtgr;
EXECUTE 'DROP TABLE zzz_' || ptable;
END;
$BODY$ LANGUAGE plpgsql VOLATILE COST 100;
#Jeremy Gustie's solution above almost works, but will do the wrong thing if the ordinals are off (or fail altogether if the re-ordered ordinals make incompatible types match). Give it a try:
CREATE TABLE test1 (one varchar, two varchar, three varchar);
CREATE TABLE test2 (three varchar, two varchar, one varchar);
INSERT INTO test1 (one, two, three) VALUES ('one', 'two', 'three');
INSERT INTO test2 SELECT * FROM test1;
SELECT * FROM test2;
The results show the problem:
testdb=> select * from test2;
three | two | one
-------+-----+-------
one | two | three
(1 row)
You can remedy this by specifying the column names in the insert:
INSERT INTO test2 (one, two, three) SELECT * FROM test1;
That gives you what you really want:
testdb=> select * from test2;
three | two | one
-------+-----+-----
three | two | one
(1 row)
The problem comes when you have legacy that doesn't do this, as I indicated above in my comment on peufeu's reply.
Update: It occurred to me that you can do the same thing with the column names in the INSERT clause by specifying the column names in the SELECT clause. You just have to reorder them to match the ordinals in the target table:
INSERT INTO test2 SELECT three, two, one FROM test1;
And you can of course do both to be very explicit:
INSERT INTO test2 (one, two, three) SELECT one, two, three FROM test1;
That gives you the same results as above, with the column values properly matched.
The order of the columns is totally irrelevant in relational databases
Yes.
For instance if you use Python, you would do :
cursor.execute( "SELECT id, name FROM users" )
for id, name in cursor:
print id, name
Or you would do :
cursor.execute( "SELECT * FROM users" )
for row in cursor:
print row['id'], row['name']
But no sane person would ever use positional results like this :
cursor.execute( "SELECT * FROM users" )
for id, name in cursor:
print id, name
Well, it's a visual goody for DBA's and can be implemented to the engine with minor performance loss. Add a column order table to pg_catalog or where it's suited best. Keep it in memory and use it before certain queries. Why overthink such a small eye candy.
# Milen A. Radev
The irrelevant need from having a set order of columns is not always defined by the query that pulls them. In the values from pg_fetch_row does not include the associated column name and therefore would require the columns to be defined by the SQL statement.
A simple select * from would require innate knowledge of the table structure, and would sometimes cause issues if the order of the columns were to change.
Using pg_fetch_assoc is a more reliable method as you can reference the column names, and therefore use a simple select * from.

PLSQL procedure for automatic column type changing

Let's assume following table:
drop table test1;
create table test1(
A number(10)
);
insert into test1 values (1);
insert into test1 values (10);
So as you can see table TEST1 is already populated. What i need to do is to change types of column A to varchar2. Since this column has values we can't just use following code:
alter table test1 modify A varchar2(10);
So i have wrote stored procedure which:
Renames column A to A1 ->
Then adds new column called A of type varchar2 ->
Then updates column A with values from column A1 ->
And ultimately drops old column A1.
Code which runs this process is following:
create or replace procedure change_col_type_to_varchar2(p_tab in varchar2, p_col in varchar2)
is
v_string clob;
cursor cur is
select column_name
from all_tab_columns
where table_name = upper(p_tab) and
column_name in (select regexp_substr(p_col,'[^,]+', 1, level) from dual
connect by regexp_substr(p_col, '[^,]+', 1, level) is not null);
begin
for i in cur loop
v_string := 'alter table ' || p_tab || ' rename column ' || i.column_name || ' to ' || i.column_name || '1' || ';';
dbms_lob.append(v_string,''||chr(10)||'');
dbms_lob.append(v_string, 'alter table ' || p_tab || ' add ' || i.column_name || ' varchar2(10);');
dbms_lob.append(v_string,''||chr(10)||'');
dbms_lob.append(v_string, 'update ' || p_tab || ' set ' || i.column_name || ' = ' || i.column_name || '1' || ';');
dbms_lob.append(v_string,''||chr(10)||'');
dbms_lob.append(v_string, 'alter table ' || p_tab || ' drop column ' || i.column_name || '1' || ';');
EXECUTE IMMEDIATE v_string;
DBMS_OUTPUT.PUT_LINE(v_string);
v_string := NULL;
end loop;
end;
I'am trying to apply this procedure to TEST1:
begin
change_col_type_to_varchar2('TEST1', 'A');
end;
And get error:
Error report -
ORA-23290: This operation may not be combined with any other operation
ORA-06512: at "YAVORSKYIY_DM.CHANGE_COL_TYPE_TO_VARCHAR2", line 19
ORA-06512: at "YAVORSKYIY_DM.CHANGE_COL_TYPE_TO_VARCHAR2", line 19
ORA-06512: at line 2
23290. 00000 - "This operation may not be combined with any other operation"
*Cause: ALTER TABLE RENAME COLUMN/CONSTRAINT operation was given in
conjunction with another ALTER TBALE Operation. This is not
allowed.
*Action: Ensure that RENAME COLUMN/CONSTRAINT is the only operation
specified in the ALTER TABLE.
But just typing :
alter table test1 rename column A to A1;
alter table test1 add A varchar2(100);
update test1 set A = A1;
alter table test1 drop column A1;
Works perfect.
Does anybody have any ideas about how to overcome this problem?
Appreciate your help.
the below will do what you asked for.
declare
procedure change_col_type_to_varchar2(p_tab in varchar2, p_col in varchar2)
is
v_string clob;
cursor cur is
select column_name
from all_tab_columns
where table_name = upper(p_tab) and
column_name in (select regexp_substr(p_col,'[^,]+', 1, level)
from dual
connect by regexp_substr(p_col, '[^,]+', 1, level) is not null);
begin
for i in cur loop
v_string := 'alter table ' || p_tab || ' rename column ' || i.column_name || ' to ' || i.column_name || '1';
execute immediate v_string;
v_string := 'alter table ' || p_tab || ' add ' || i.column_name || ' varchar2(10)';
execute immediate v_string;
v_string := 'update ' || p_tab || ' set ' || i.column_name || ' = ' || i.column_name || '1' ;
execute immediate v_string;
v_string := 'alter table ' || p_tab || ' drop column ' || i.column_name || '1' ;
execute immediate v_string;
v_string := NULL;
end loop;
end;
begin
DBMS_OUTPUT.PUT_LINE('Before calling');
change_col_type_to_varchar2('TEST1','A');
DBMS_OUTPUT.PUT_LINE('After calling');
end;
Well, execute each statement alone, instead of concatenating them. And you don't need LOBs, varchar2 for each one should be enough.
I propose other algorithm.
create new table 'table2' with varchar column;
select all values from table1.A and insert to table2 with to_char() conversion;
drop table1;
rename table2 to table1;
profit!

Updating a column matching a specific pattern in all table in an oracle database

I need to update a column matching a specific pattern in all tables in an oracle database.
For example I have in all tables this column *_CID with is a foreign key to master table witch has a primary key CID
Thanks
You can use the naming convention and query all_tab_columns
declare
cursor c is
select table_owner , column_name, table_name from all_tab_columns where column_name like '%_CID';
begin
for x in c loop
execute immediate 'update ' || x.table_owner || '.' || x.table_name ||' set ' || x.column_name||' = 0';
end loop;
end;
If you have valid Fk's you can also use all_tab_constraints the fetch enabled FK's for your main table and fetch the columns name of the r_constraint_name.
I found a solution to my question:
BEGIN
FOR x IN (SELECT owner, table_name, column_name FROM all_tab_columns) LOOP
EXECUTE IMMEDIATE 'update ' || x.owner || '.' || x.table_name ||' set ' || x.column_name||' = 0 where '||x.column_name||' = 1';
END LOOP;
END;
thanks

Best way to maintain daywise interval partitions in 11g

I had created a sql script in 11g that would drop all partitions having high value less than 60 days in all partitioned tables in the database
DECLARE
TNAME VARCHAR2 (300);
PNAME VARCHAR2 (300);
HIGHVAL VARCHAR2 (3000);
POSITION SMALLINT;
VAL LONG;
CURSOR C1
IS
SELECT TABLE_NAME, PARTITION_NAME, PARTITION_POSITION, HIGH_VALUE
FROM USER_TAB_PARTITIONS
WHERE TABLE_NAME NOT LIKE '%$%'
AND TABLE_NAME NOT LIKE 'BIN%';
BEGIN
OPEN C1;
LOOP
FETCH C1
INTO TNAME, PNAME, POSITION, VAL;
HIGHVAL := VAL;
EXIT WHEN C1%NOTFOUND;
IF TO_DATE (SUBSTR (HIGHVAL, 10, 11), 'RRRR-MM-DD') <
TRUNC (SYSDATE)
- 60
THEN
IF POSITION = 1
THEN
DBMS_OUTPUT.PUT_LINE ('ALTER TABLE ' || TNAME
|| ' SET INTERVAL();'
);
END IF;
DBMS_OUTPUT.PUT_LINE ( 'ALTER TABLE '
|| TNAME
|| ' DROP PARTITION '
|| PNAME
|| ' UPDATE GLOBAL INDEXES PARALLEL 2;'||CHR(10)
|| '--DROPPED'
|| '--'
|| TO_DATE (SUBSTR (HIGHVAL, 10, 11),
'RRRR-MM-DD'
)
);
IF POSITION = 1
THEN
DBMS_OUTPUT.PUT_LINE
( 'ALTER TABLE '
|| TNAME
|| ' SET INTERVAL(NUMTODSINTERVAL(1,''DAY''));'
);
END IF;
END IF;
END LOOP;
COMMIT;
CLOSE C1;
END;
/
I'm executing the generated SQL text
Kindly advice if this correct and any room for enhancement???
A few hints:
It's a perfect place for implicit cursor, so you don't need to manually declare variables, fetch, open & close, ...
Filter high value in the query, earlier is better
Use EXECUTE IMMEDIATE to apply changes instead of manually executing whatever gets printed
You don't need to commit, since it's all DDL
The code:
BEGIN
FOR p IN (SELECT TABLE_NAME, PARTITION_NAME, PARTITION_POSITION, HIGH_VALUE
FROM USER_TAB_PARTITIONS
WHERE TABLE_NAME NOT LIKE '%$%'
AND TABLE_NAME NOT LIKE 'BIN%'
AND TO_DATE (SUBSTR (HIGH_VALUE, 10, 11), 'RRRR-MM-DD') < TRUNC (SYSDATE) - 60)
LOOP
IF p.PARTITION_POSITION = 1
THEN
EXECUTE IMMEDIATE 'ALTER TABLE ' || p.TABLE_NAME || ' SET INTERVAL()';
END IF;
EXECUTE IMMEDIATE 'ALTER TABLE ' || p.TABLE_NAME
|| 'DROP PARTITION ' || p.PARTITION_NAME
|| ' UPDATE GLOBAL INDEXES PARALLEL 2';
IF p.PARTITION_POSITION = 1
THEN
EXECUTE IMMEDIATE 'ALTER TABLE ' || p.TABLE_NAME
|| ' SET INTERVAL(NUMTODSINTERVAL(1,''DAY''));';
END IF;
END LOOP;
END;
/
And a few warnings:
Watch out for UPDATE GLOBAL INDEXES, it does not work with IOT tables (if you use them) (I was wrong with this one)
Watch out for resetting/setting intervals. The general rule is that you can't drop last non-interval partition. Guessing this would be position 1 is risky. Better to rely on user_tab_partitions.interval flag.