Best way to maintain daywise interval partitions in 11g - sql

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.

Related

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!

Oracle procedure to delete records in all tables of an owner

I am trying to create an Oracle procedure to delete records from multiple tables of an owner based upon a distinct count condition:
Firstly I am trying to obtain the tables for which I want to delete those records with this query:
SELECT * FROM ALL_TABLES WHERE OWNER = 'Lorik' AND TABLE_NAME LIKE 'UT_%';
This results in a total of 300 tables, now all of those tables have a column named: DATE_INC
I am trying to delete records from all of the tables if this COUNT(DISTINCT DATE_INC) > 5.
Assuming that one of those 300 tables is named UT_NAMES:
SELECT COUNT(DISTINCT DATE_INC) FROM Lorik.UT_NAMES;
So if the count exceeds 5, then I want to delete the records with the minimum date:
DELETE MIN(DATE_INC) FROM Lorik.UT_NAMES;
Can someone please link these steps together so I can loop through each table of that owner and obtain the distinct date count and delete records based upon the above cited condition.
Thanks in advance!
You can use 'EXECUTE IMMEDIATE' in PL/SQL to accomplish your goal:
DECLARE
strTable VARCHAR2(32767);
nCount NUMBER;
BEGIN
FOR aRow IN (SELECT *
FROM ALL_TABLES
WHERE OWNER = 'Lorik' AND
TABLE_NAME LIKE 'UT_%')
LOOP
strTable := aRow.OWNER || '.' || aRow.TABLE_NAME;
EXECUTE IMMEDIATE 'SELECT COUNT(DISTINCT DATE_INC) FROM ' || strTable
INTO nCount;
IF nCount > 5 THEN
EXECUTE IMMEDIATE 'DELETE FROM ' || strTable ||
' WHERE DATE_INC = (SELECT MIN(DATE_INC) ' ||
'FROM ' || strTable || ')';
END IF;
END LOOP;
END;
Not tested on animals - you'll be first! :-)
As pointed out by #Andrew this seems to be very basic processes.
Declare some variables.
Open a cursor.
Use dynamic sql to count
Use dynamic sql to delete
Add some log information
_
declare
v_cnt number;
v_sql varchar2(1000);
begin
for cur in (SELECT * FROM ALL_TABLES WHERE OWNER = 'HR' AND TABLE_NAME LIKE 'E%')
loop
v_sql := 'select count(distinct department_id||''date_inc'') from '||cur.owner||'. '||cur.table_name;
execute immediate v_sql into v_cnt;
dbms_output.put_line (cur.table_name || ': ' || v_cnt);
if v_cnt > 5 then
v_sql := 'delete from '||cur.owner||'. '||cur.table_name || ' where date_inc = (select min (date_inc) from ' ||cur.owner||'. '||cur.table_name || ')';
dbms_output.put_line (v_sql);
-- execute immediate v_sql;
end if;
end loop;
rollback;
-- commit;
end;
A little bit simpler dynamic SQL for deleting rows, as it uses a local variable:
declare
l_cnt number; -- counter variable
l_min_date date; -- MIN(date_inc)
begin
for cur_t in (select table_name from all_tables
where owner = 'Lorik' -- are you sure it is not uppercase, LORIK?
and table_name like 'UT%' -- underline is wildcard character so you don't need it
)
loop
execute immediate 'select count(distinct date_inc), min(date_inc) from ' ||
cur_t.table_name into l_cnt, l_min_date;
if l_cnt > 5 then
execute immediate 'delete from ' || cur_t.table_name ||
' where date_inc = ' || l_min_date_inc;
end if;
end loop;
end;
/

configuring the oracle procedure so that it should accept the input value

I have created an procedure which delete the 3 months old partition from the table now i want to make the below procedure configurable enough such that it should accept the count from the user so please advise how can i modify the below procedure
create or replace
PROCEDURE Delete_partitions
/*
This procedure will delete partitions for the following tables:
TEMPTABLE
*/
BEGIN
FOR cc IN
(
SELECT partition_name, high_value
FROM user_tab_partitions
WHERE table_name = 'TEMPTABLE'
)
dbms_output.put_line('starting to drop partition ');
LOOP
EXECUTE IMMEDIATE 'BEGIN
IF sysdate >= ADD_MONTHS(' || cc.high_value || ', 2) THEN
EXECUTE IMMEDIATE
''ALTER TABLE TEMPTABLE DROP PARTITION ' || cc.partition_name || '
'';
END IF;
dbms_output.put_line('drop partition completed');
END;';
END LOOP;
exception
when others then
dbms_output.put_line(SQLERRM);
END;
/
Add some parameters to it:
create or replace
PROCEDURE Delete_partitions(cnt in number)
/*
This procedure will delete partitions for the following tables:
TEMPTABLE
*/
BEGIN
FOR cc IN
(
SELECT partition_name, high_value
FROM user_tab_partitions
WHERE table_name = 'TEMPTABLE'
)
dbms_output.put_line('starting to drop partition ');
LOOP
EXECUTE IMMEDIATE 'BEGIN
IF sysdate >= ADD_MONTHS(' || cc.high_value || ', ' || cnt-1 || ') THEN
EXECUTE IMMEDIATE
''ALTER TABLE TEMPTABLE DROP PARTITION ' || cc.partition_name || '
'';
END IF;
dbms_output.put_line('drop partition completed');
END;';
END LOOP;
exception
when others then
dbms_output.put_line(SQLERRM);
END;
/

query each column of a table in a loop - Oracle Database

I'm working with an oracle database and what I basically need to do is to count the number of NULL fields per column in a certain table.
something like that:
DECLARE
BlankCount number(20);
i number(2) := 1;
BEGIN
loop that would take each column individualy and exit after the last one
SELECT COUNT(*) INTO BlankCount FROM name_of_my_table
DBMS_OUTPUT.PUT_LINE('Column '||i||' has '||BlankCount||' empty cells');
i := i + 1;
END LOOP;
END;
I just couldn't find anything that would do the loop part.
It would also be nice if instead of just numbering them (with the i) I could display the column name (but that is not very important).
Thank you!
Something like this:
declare
mytable varchar(32) := 'MY_TABLE';
cursor s1 (mytable varchar2) is
select column_name
from user_tab_columns
where table_name = mytable
and nullable = 'Y';
mycolumn varchar2(32);
query_str varchar2(100);
mycount number;
begin
open s1 (mytable);
loop
fetch s1 into mycolumn;
exit when s1%NOTFOUND;
query_str := 'select count(*) from ' || mytable || ' where ' || mycolumn || ' is null';
execute immediate query_str into mycount;
dbms_output.put_line('Column ' || mycolumn || ' has ' || mycount || ' null values');
end loop;
end;
Try using cursor approach and Dynamic SQL as mentioned in this thread: How to loop through columns in an oracle pl/sql cursor
HTH.

How to get Oracle create table statement in SQL*Plus

I have a table that exists in an Oracle database, but doesn't show on my list of tables in the tool SQL Developer. However, if I go to SQL*Plus, and do a
select table_name from user_tables;
I get the table listed. If I type
desc snp_clearinghouse;
it shows me the fields. I'd like to get the create statement, because I need to add a field. I can modify the table to add the field, but I still need the create statement to put into our source control. What pl/sql statement is used to get the create statement for a table?
From Get table and index DDL the easy way:
set heading off;
set echo off;
Set pages 999;
set long 90000;
spool ddl_list.sql
select dbms_metadata.get_ddl('TABLE','DEPT','SCOTT') from dual;
select dbms_metadata.get_ddl('INDEX','DEPT_IDX','SCOTT') from dual;
spool off;
Same as above but generic script found here gen_create_table_script.sql
-- #############################################################################################
--
-- %Purpose: Generate 'CREATE TABLE' Script for an existing Table in the database
--
-- Use: SYSTEM, SYS or user having SELECT ANY TABLE system privilege
--
-- #############################################################################################
--
set serveroutput on size 200000
set echo off
set feedback off
set verify off
set showmode off
--
ACCEPT l_user CHAR PROMPT 'Username: '
ACCEPT l_table CHAR PROMPT 'Tablename: '
--
DECLARE
CURSOR TabCur IS
SELECT table_name,owner,tablespace_name,
initial_extent,next_extent,
pct_used,pct_free,pct_increase,degree
FROM sys.dba_tables
WHERE owner=upper('&&l_user')
AND table_name=UPPER('&&l_table');
--
CURSOR ColCur(TableName varchar2) IS
SELECT column_name col1,
DECODE (data_type,
'LONG', 'LONG ',
'LONG RAW', 'LONG RAW ',
'RAW', 'RAW ',
'DATE', 'DATE ',
'CHAR', 'CHAR' || '(' || data_length || ') ',
'VARCHAR2', 'VARCHAR2' || '(' || data_length || ') ',
'NUMBER', 'NUMBER' ||
DECODE (NVL(data_precision,0),0, ' ',' (' || data_precision ||
DECODE (NVL(data_scale, 0),0, ') ',',' || DATA_SCALE || ') '))) ||
DECODE (NULLABLE,'N', 'NOT NULL',' ') col2
FROM sys.dba_tab_columns
WHERE table_name=TableName
AND owner=UPPER('&&l_user')
ORDER BY column_id;
--
ColCount NUMBER(5);
MaxCol NUMBER(5);
FillSpace NUMBER(5);
ColLen NUMBER(5);
--
BEGIN
MaxCol:=0;
--
FOR TabRec in TabCur LOOP
SELECT MAX(column_id) INTO MaxCol FROM sys.dba_tab_columns
WHERE table_name=TabRec.table_name
AND owner=TabRec.owner;
--
dbms_output.put_line('CREATE TABLE '||TabRec.table_name);
dbms_output.put_line('( ');
--
ColCount:=0;
FOR ColRec in ColCur(TabRec.table_name) LOOP
ColLen:=length(ColRec.col1);
FillSpace:=40 - ColLen;
dbms_output.put(ColRec.col1);
--
FOR i in 1..FillSpace LOOP
dbms_output.put(' ');
END LOOP;
--
dbms_output.put(ColRec.col2);
ColCount:=ColCount+1;
--
IF (ColCount < MaxCol) THEN
dbms_output.put_line(',');
ELSE
dbms_output.put_line(')');
END IF;
END LOOP;
--
dbms_output.put_line('TABLESPACE '||TabRec.tablespace_name);
dbms_output.put_line('PCTFREE '||TabRec.pct_free);
dbms_output.put_line('PCTUSED '||TabRec.pct_used);
dbms_output.put_line('STORAGE ( ');
dbms_output.put_line(' INITIAL '||TabRec.initial_extent);
dbms_output.put_line(' NEXT '||TabRec.next_extent);
dbms_output.put_line(' PCTINCREASE '||TabRec.pct_increase);
dbms_output.put_line(' )');
dbms_output.put_line('PARALLEL '||TabRec.degree);
dbms_output.put_line('/');
END LOOP;
END;
/
If you are using oracle SQLcl command-line client, the simplest way is to use the ddl built-in command. For example
ddl ownername.tablename
You will get the complete definition for that table. Warning: it could be very long based on your target table.