Truncate partitions older than 2 months - oracle

How to truncate partitions with data older than 2 months?
For an example, i have below table/partition names:
select table_name, partition_name from all_tab_partitions where table_name='TABLENAME';
TABLENAME partitionname1_P30 30
TABLENAME partitionname2_P60 60
TABLENAME partitionname3_P90 90
TABLENAME partitionname4_P120 120
TABLENAME partitionname5_P150 150
TABLENAME partitionname6_P180 180
TABLENAME partitionname7_210 210
TABLENAME partitionname8_P240 240
TABLENAME partitionname9_P270 270
TABLENAME partitionname10_P300 300
TABLENAME partitionname11_P330 330
TABLENAME partitionname12_P360 360
Table is partitioned per month. If we're currently on September, how do I truncate partitions older than 2 months?
Expectation is that only records from Aug-Sep (partitionname8-9) will remain while the rest will be truncated.
CREATE TABLE dbo1.TABLENAME
( PARTITION_ID NUMBER(4, 0) NOT NULL,
TABLE_DATE DATE NOT NULL,
TABLE_TIMESTAMP NUMBER(19, 0) NOT NULL,
TABLE_BUNDLE_ID VARCHAR2(240 BYTE) NOT NULL,
TABLE_TYPE NUMBER(8, 0) NOT NULL,
TABLE_SEVERITY NUMBER(19, 0) NOT NULL,
TABLE_FACILITY NUMBER(19, 0) NOT NULL,
TABLE_HOST VARCHAR2(120 BYTE) NOT NULL,
TABLE_PROCESS VARCHAR2(240 BYTE) NOT NULL,
TABLE_SYSTEM VARCHAR2(240 BYTE) NOT NULL,
TABLE_SESSION_ID VARCHAR2(240 BYTE) NOT NULL,
TABLE_PRINCIPAL VARCHAR2(120 BYTE) NOT NULL,
OBJECT_ID VARCHAR2(120 BYTE),
OBJECT_TYPE VARCHAR2(2 BYTE),
CLIENT_HOST VARCHAR2(120 BYTE),
ACCESS_HOST VARCHAR2(120 BYTE),
SCOPE_ID VARCHAR2(120 BYTE),
STATUS NUMBER(19, 0),
OBJECT_HISTORY NUMBER(19, 0),
TABLE_DETAILS VARCHAR2(4000 BYTE)
)
PARTITION BY RANGE (PARTITION_ID)
(
PARTITION partitionname1_P30 VALUES LESS THAN (30)
,<repeat partition by 30s up to 360, total of 12 partitions>

You can do it like this:
DECLARE
CURSOR PartTables IS
SELECT TABLE_NAME, PARTITION_NAME, HIGH_VALUE
FROM USER_TAB_PARTITIONS
WHERE TABLE_NAME = 'TABLENAME';
highValue TIMESTAMP;
BEGIN
FOR aTab IN PartTables LOOP
EXECUTE IMMEDIATE 'BEGIN :ret := '||aTab.HIGH_VALUE||'; END;' USING OUT highValue;
IF highValue < ADD_MONTHS(SYSDATE, -2) THEN
EXECUTE IMMEDIATE 'ALTER TABLE TABLENAME TRUNCATE PARTITION '||aTab.PARTITION_NAME||' UPDATE INDEXES';
END IF;
END LOOP;
END;
This would work for a RANGE or INTERVAL based partitions, however in this case your requirement is rather useless because you would keep empty partitions for ever. Usually you drop old partitions, for that just replace TRUNCATE by DROP.
In case your partition is base on LIST, i.e. month number the solution would be this:
DECLARE
CURSOR PartTables IS
SELECT TABLE_NAME, PARTITION_NAME, HIGH_VALUE
FROM USER_TAB_PARTITIONS
WHERE TABLE_NAME = 'TABLENAME';
highValue INTEGER;
BEGIN
FOR aTab IN PartTables LOOP
EXECUTE IMMEDIATE 'BEGIN :ret := '||aTab.HIGH_VALUE||'; END;' USING OUT highValue;
IF highValue NOT IN (
EXTRACT(MONTH FROM SYSDATE),
EXTRACT(MONTH FROM ADD_MONTHS(SYSDATE, -1))
)
THEN
EXECUTE IMMEDIATE 'ALTER TABLE TABLENAME TRUNCATE PARTITION '||aTab.PARTITION_NAME||' UPDATE INDEXES';
END IF;
END LOOP;
END;
Based on your strange partition definition, the conditions would be
IF highValue NOT IN (
30*CEIL(TO_CHAR(SYSDATE, 'fmddd')/30),
30*CEIL(TO_CHAR(ADD_MONTHS(SYSDATE, -1), 'fmddd')/30)
)
THEN
but you may run into issues if you run the procedure between 26th - 31st of December.

Related

Add a new partition to other partition based on the date column and 1 partition for each day

I want to Design a table like table F and partition it in such a way that a new partition is created by adding a new data assuming it is not in the existing partitions. (partition based on the date column and 1 partition for each day) . I am new in oracle, please help me ,what is the best idea ? How can I write this code .
Table F is :
DATE Amount ID
2015-05-18 1000 1
2015-05-19 2000 2
2015-05-20 3000 3
2015-05-21 4000 4
2015-05-21 5000 5
2015-05-21 3000 6
2015-05-22 2002 7
You can create several different partitions on a date column ie ( daily, weekly, monthly, quarterly or yearly) and include a local or global index on the column you need to decide what fits your needs
Below is an example of a weekly PARTITION with a global index. The PARTITIONs will be automatically added with a system generated name
when a new date is inserted into the table.
/* weekly PARTITION */
CREATE TABLE t1 (
seq_num NUMBER GENERATED BY DEFAULT AS IDENTITY (START WITH 1) NOT NULL,
dt DATE)
PARTITION BY RANGE (dt)
INTERVAL ( NUMTODSINTERVAL (7, 'DAY') ) (
PARTITION OLD_DATA VALUES LESS THAN (DATE '2022-04-01')
);
/
INSERT into t1 (dt)
with dt (dt, interv) as (
select date '2022-04-01', numtodsinterval(1,'DAY') from dual
union all
select dt.dt + interv, interv from dt
where dt.dt + interv < date '2022-08-31')
select dt from dt;
/
create index t1_global_ix on T1 (dt);
/
Every time a new partition is created Oracle generates a system name, which is quite cryptic
Here is a list of the PARTITION names, which Oracle generated when I loaded the data above
SELECT PARTITION_NAME
FROM USER_TAB_PARTITIONS
WHERE TABLE_NAME = 'T1'
PARTITION_NAME
OLD_DATA
SYS_P458773
SYS_P458774
SYS_P458775
SYS_P458776
SYS_P458777
SYS_P458778
SYS_P458779
SYS_P458780
SYS_P458781
SYS_P458782
SYS_P458783
SYS_P458784
SYS_P458785
SYS_P458786
SYS_P458787
SYS_P458788
SYS_P458789
SYS_P458790
SYS_P458791
SYS_P458792
SYS_P458793
SYS_P458794
Although PARTITION management will work with system GENERATED PARTITION names, I use the procedure below to rename them to something more meaningful.
Let's create and run the procedure and take a look at the names again. As you can see, since we are working with weekly partitions the name is P_ for partittion YYYY 4 digit year the PARTITION is in, W for Week of the year, and ## for the week number within the year.
I would suggest using the scheduler to run this process at least once a day. You can run it as many times as you want as it will not cause any harm.
CREATE OR REPLACE PROCEDURE MaintainPartitions IS EXPRESSION_IS_OF_WRONG_TYPE EXCEPTION;
PRAGMA EXCEPTION_INIT(EXPRESSION_IS_OF_WRONG_TYPE, -6550);
CURSOR PartTables IS
SELECT TABLE_NAME, INTERVAL
FROM USER_PART_TABLES
WHERE PARTITIONING_TYPE = 'RANGE'
ORDER BY TABLE_NAME;
CURSOR TabParts(aTableName VARCHAR2) IS
SELECT PARTITION_NAME, HIGH_VALUE
FROM USER_TAB_PARTITIONS
WHERE regexp_like(partition_name,'^SYS_P[[:digit:]]{1,10}') AND
TABLE_NAME = aTableName AND
table_name not like 'BIN$%'
and interval is not null
ORDER BY PARTITION_POSITION;
ym INTERVAL YEAR TO MONTH;
ds INTERVAL DAY TO SECOND;
newPartName VARCHAR2(30);
PERIOD TIMESTAMP;
BEGIN
FOR aTab IN PartTables LOOP
BEGIN
EXECUTE IMMEDIATE 'BEGIN :ret := '||aTab.INTERVAL||'; END;' USING OUT ds;
ym := NULL;
EXCEPTION
WHEN EXPRESSION_IS_OF_WRONG_TYPE THEN
EXECUTE IMMEDIATE 'BEGIN :ret := '||aTab.INTERVAL||'; END;' USING OUT ym;
ds := NULL;
END;
FOR aPart IN TabParts(aTab.TABLE_NAME) LOOP
EXECUTE IMMEDIATE 'BEGIN :ret := '||aPart.HIGH_VALUE||'; END;' USING OUT PERIOD;
IF ds IS NOT NULL THEN
IF ds >= INTERVAL '7' DAY THEN
-- Weekly partition
EXECUTE IMMEDIATE 'BEGIN :ret := TO_CHAR('||aPart.HIGH_VALUE||' - :int, :fmt); END;' USING OUT newPartName, INTERVAL '1' DAY, '"P_"IYYY"W"IW';
ELSE
-- Daily partition
EXECUTE IMMEDIATE 'BEGIN :ret := TO_CHAR('||aPart.HIGH_VALUE||' - :int, :fmt); END;' USING OUT newPartName, INTERVAL '1' DAY, '"P_"YYYYMMDD';
END IF;
ELSE
IF ym = INTERVAL '3' MONTH THEN
-- Quarterly partition
EXECUTE IMMEDIATE 'BEGIN :ret := TO_CHAR('||aPart.HIGH_VALUE||' - :int, :fmt); END;' USING OUT newPartName, INTERVAL '1' DAY, '"P_"YYYY"Q"Q';
ELSE
-- Monthly partition
EXECUTE IMMEDIATE 'BEGIN :ret := TO_CHAR('||aPart.HIGH_VALUE||' - :int, :fmt); END;' USING OUT newPartName, INTERVAL '1' DAY, '"P_"YYYYMM';
END IF;
END IF;
IF newPartName <> aPart.PARTITION_NAME THEN
EXECUTE IMMEDIATE 'ALTER TABLE '||aTab.TABLE_NAME||' RENAME PARTITION '||aPart.PARTITION_NAME||' TO '||newPartName;
END IF;
END LOOP;
END LOOP;
END MaintainPartitions;
/
EXEC MaintainPartitions
SELECT PARTITION_NAME
FROM USER_TAB_PARTITIONS
WHERE TABLE_NAME = 'T1'
PARTITION_NAME
OLD_DATA
P_2022W14
P_2022W15
P_2022W16
P_2022W17
P_2022W18
P_2022W19
P_2022W20
P_2022W21
P_2022W22
P_2022W23
P_2022W24
P_2022W25
P_2022W26
P_2022W27
P_2022W28
P_2022W29
P_2022W30
P_2022W31
P_2022W32
P_2022W33
P_2022W34
SELECT COUNT(*) FROM USER_TAB_PARTITIONS
COUNT(*)
31
Next step is setting up your RETENTION table. There should be an entry for each interval range PARTITION.
The RETENTION value is for you to decide. In my example, I chose 30 days fir table T1. This means, when the high value for a PARTITION is greater than 30 days its eligible to be dropped. So chose wisely when setting up these values.
Note: I listed the names of other tables to show how each table has its own value.
CREATE TABLE PARTITION_RETENTION (
seq_num NUMBER GENERATED BY DEFAULT AS IDENTITY (START WITH 1) NOT NULL,
TABLE_NAME VARCHAR2(30),
RETENTION INTERVAL DAY(3) TO SECOND(0),
CONSTRAINT
partition_retention_pk primary key (table_name),
CONSTRAINT CHK_NON_ZERO_DAYS CHECK (
RETENTION > INTERVAL '0' DAY
),
CONSTRAINT CHK_WHOLE_DAYS CHECK (
EXTRACT(HOUR FROM RETENTION) = 0
AND EXTRACT(MINUTE FROM RETENTION) = 0
AND EXTRACT(SECOND FROM RETENTION) = 0
)
);
insert into PARTITION_RETENTION (TABLE_NAME, RETENTION)
select 'T0', interval '10' day from dual union all
select 'T1', interval '30' day from dual union all
select 'T2', interval '15' day from dual union all
select 'T3', interval '30' day from dual union all
select 'T4', 15 * interval '1' day from dual union all
select 'T5', 5 * interval '1 00:00:00' day to second from dual;
Below are 3 procedures that need to be created.
The ddl procedure is a wrapper, which shows you what is being processed and how long it takes.
The rebuild_index procedure is obvious it rebuilds any invalid indexes. As I mentioned above if you are using a global index and a PARTITION is dropped then the index needs to be rebuilt. I hardcoded parallel 4 in this example but if you have plenty if CPU power you may want to increase the number to fit your needs.
In addition, there are other ways indexes can be marked unusable so you may want to consider scheduling that task.
Lastly, is the anonymous block. Which actually drops the PARTITIONS for, which the retention PERIOD has passed. This needs to be scheduled once a day!!
If you look carefully at the anonymous block the last step is a call to the rebuild index procedure. So if an index is unusable it will be rebuilt.
Now let's run the process and see what happens.
CREATE OR REPLACE PROCEDURE ddl(p_cmd varchar2)
authid current_user
is
t1 pls_integer;
BEGIN
t1 := dbms_utility.get_time;
dbms_output.put_line(p_cmd);
execute immediate p_cmd;
dbms_output.put_line((dbms_utility.get_time - t1)/100 || ' seconds');
END;
/
CREATE OR REPLACE PROCEDURE rebuild_index
authid current_user
is
BEGIN
for i in (
select index_owner, index_name, partition_name, 'partition' ddl_type
from all_ind_partitions
where status = 'UNUSABLE'
union all
select owner, index_name, null, null
from all_indexes
where status = 'UNUSABLE'
)
loop
if i.ddl_type is null then
ddl('alter index '||i.index_owner||'.'||i.index_name||' rebuild parallel 4 online');
else
ddl('alter index '||i.index_owner||'.'||i.index_name||' modify '||i.ddl_type||' '||i.partition_name||' rebuild parallel 4 online');
end if;
end loop;
END;
/
DECLARE
CANNOT_DROP_LAST_PARTITION EXCEPTION;
PRAGMA EXCEPTION_INIT(CANNOT_DROP_LAST_PARTITION, -14758);
CANNOT_DROP_ONLY_ONE_PARTITION EXCEPTION;
PRAGMA EXCEPTION_INIT(CANNOT_DROP_ONLY_ONE_PARTITION, -14083);
ts TIMESTAMP;
CURSOR TablePartitions IS
SELECT TABLE_NAME, PARTITION_NAME, p.HIGH_VALUE, t.INTERVAL, RETENTION, DATA_TYPE
FROM USER_PART_TABLES t
JOIN USER_TAB_PARTITIONS p USING (TABLE_NAME)
JOIN USER_PART_KEY_COLUMNS pk ON pk.NAME = TABLE_NAME
JOIN USER_TAB_COLS tc USING (TABLE_NAME, COLUMN_NAME)
JOIN PARTITION_RETENTION r USING (TABLE_NAME)
WHERE pk.object_type = 'TABLE' AND
t.partitioning_type = 'RANGE' AND
REGEXP_LIKE (tc.data_type, '^DATE$|^TIMESTAMP.*');
BEGIN
FOR aPart IN TablePartitions LOOP
EXECUTE IMMEDIATE 'BEGIN :ret := '||aPart.HIGH_VALUE||'; END;' USING OUT ts;
IF ts < SYSTIMESTAMP - aPart.RETENTION THEN
BEGIN
ddl('alter table '||aPart.TABLE_NAME||' drop partition '||aPart.partition_name);
EXCEPTION
WHEN CANNOT_DROP_ONLY_ONE_PARTITION THEN
DBMS_OUTPUT.PUT_LINE('Cant drop the only partition '||aPart.PARTITION_NAME ||' from table '||aPart.TABLE_NAME);
ddl('ALTER TABLE '||aPart.TABLE_NAME||' TRUNCATE PARTITION '||aPart.PARTITION_NAME);
WHEN CANNOT_DROP_LAST_PARTITION THEN
BEGIN
DBMS_OUTPUT.PUT_LINE('Drop last partition '||aPart.PARTITION_NAME ||' from table '||aPart.TABLE_NAME);
EXECUTE IMMEDIATE 'ALTER TABLE '||aPart.TABLE_NAME||' SET INTERVAL ()';
ddl('alter table '||aPart.TABLE_NAME||' drop partition '||aPart.partition_name);
EXECUTE IMMEDIATE 'ALTER TABLE '||aPart.TABLE_NAME||' SET INTERVAL( '||aPart.INTERVAL||' )';
EXCEPTION
WHEN CANNOT_DROP_ONLY_ONE_PARTITION THEN
-- Depending on the order the "last" partition can be also the "only" partition at the same time
EXECUTE IMMEDIATE 'ALTER TABLE '||aPart.TABLE_NAME||' SET INTERVAL( '||aPart.INTERVAL||' )';
DBMS_OUTPUT.PUT_LINE('Cant drop the only partition '||aPart.PARTITION_NAME ||' from table '||aPart.TABLE_NAME);
ddl('ALTER TABLE '||aPart.TABLE_NAME||' TRUNCATE PARTITION '||aPart.PARTITION_NAME);
END;
END;
END IF;
END LOOP;
rebuild_index();
END;
alter table T1 drop partition OLD_DATA
.02 seconds
alter table T1 drop partition P_2022W14
.01 seconds
alter table T1 drop partition P_2022W15
.02 seconds
alter table T1 drop partition P_2022W16
.01 seconds
alter table T1 drop partition P_2022W17
.02 seconds
alter table T1 drop partition P_2022W18
.01 seconds
alter table T1 drop partition P_2022W19
.02 seconds
alter table T1 drop partition P_2022W20
.01 seconds
alter table T1 drop partition P_2022W21
.01 seconds
alter table T1 drop partition P_2022W22
.02 seconds
alter table T1 drop partition P_2022W23
.01 seconds
alter table T1 drop partition P_2022W24
.01 seconds
alter table T1 drop partition P_2022W25
.01 seconds
alter table T1 drop partition P_2022W26
.01 seconds
alter table T1 drop partition P_2022W27
.02 seconds
alter index SQL_WUKYPRGVPTOUVLCAEKUDCRCQI.T1_GLOBAL_IX rebuild parallel 4 online
.1 seconds
…
…
…
alter index SQL_WUKYPRGVPTOUVLCAEKUDCRCQI.T1_GLOBAL_IX rebuild parallel 4 online
.1 seconds
SELECT count(*) from USER_TAB_PARTITIONS
Where
table_name not like 'BIN$%'
8
SELECT PARTITION_NAME
FROM USER_TAB_PARTITIONS
WHERE TABLE_NAME = 'T1'
AND
table_name not like 'BIN$%'
P_2022W28
P_2022W29
P_2022W30
P_2022W31
P_2022W32
P_2022W33
P_2022W34
P_2022W35

How to automate partition drop and alter table activity in oracle sql developer

I need a procedure that will help me to drop partition older than 3 months (current month + last 3 older months). And then I need to create the new partition in sequence.
for example if current partition is May22, then I need to drop Jan22 and create Jan23 partition. Can someone help me with the procedure?
Here is the process we use to RENAME and drop PARTITIONs that are range INTERVAL. Just add the procedures to your scheduler.
They work great
CREATE OR REPLACE PROCEDURE ddl(p_cmd varchar2)
authid current_user
is
t1 pls_integer;
BEGIN
t1 := dbms_utility.get_time;
dbms_output.put_line(p_cmd);
execute immediate p_cmd;
dbms_output.put_line((dbms_utility.get_time - t1)/100 || ' seconds');
END;
/
CREATE TABLE PARTITION_RETENTION (
seq_num NUMBER GENERATED BY DEFAULT AS IDENTITY (START WITH 1) NOT NULL,
TABLE_NAME VARCHAR2(30),
RETENTION INTERVAL DAY(3) TO SECOND(0),
CONSTRAINT
partition_retention_pk primary key (table_name),
CONSTRAINT CHK_NON_ZERO_DAYS CHECK (
RETENTION > INTERVAL '0' DAY
),
CONSTRAINT CHK_WHOLE_DAYS CHECK (
EXTRACT(HOUR FROM RETENTION) = 0
AND EXTRACT(MINUTE FROM RETENTION) = 0
AND EXTRACT(SECOND FROM RETENTION) = 0
)
);
insert into PARTITION_RETENTION (TABLE_NAME, RETENTION)
select 'T1', interval '10' day from dual union all
select 'T3', interval '15' day from dual union all
select 'T4', 15 * interval '1' day from dual union all
select 'T5', 5 * interval '1 00:00:00' day to second from dual;
CREATE TABLE t1 (
seq_num NUMBER GENERATED BY DEFAULT AS IDENTITY (START WITH 1) NOT NULL,
dt DATE
)
PARTITION BY RANGE (dt)
INTERVAL (NUMTODSINTERVAL(7,'DAY'))
(
PARTITION OLD_DATA values LESS THAN (TO_DATE('2022-01-01','YYYY-MM-DD'))
);
/
INSERT into t1 (dt)
with dt (dt, interv) as (
select date '2022-01-01', numtodsinterval(1,'DAY') from dual
union all
select dt.dt + interv, interv from dt
where dt.dt + interv < date '2022-02-01')
select dt from dt;
/
create index t1_global_ix on t1 (dt);
/
CREATE OR REPLACE PROCEDURE MaintainPartitions IS EXPRESSION_IS_OF_WRONG_TYPE EXCEPTION;
PRAGMA EXCEPTION_INIT(EXPRESSION_IS_OF_WRONG_TYPE, -6550);
CURSOR PartTables IS
SELECT TABLE_NAME, INTERVAL
FROM USER_PART_TABLES
WHERE PARTITIONING_TYPE = 'RANGE'
ORDER BY TABLE_NAME;
CURSOR TabParts(aTableName VARCHAR2) IS
SELECT PARTITION_NAME, HIGH_VALUE
FROM USER_TAB_PARTITIONS
WHERE regexp_like(partition_name,'^SYS_P[[:digit:]]{1,10}') AND
TABLE_NAME = aTableName AND
table_name not like 'BIN$%'
and interval is not null
ORDER BY PARTITION_POSITION;
ym INTERVAL YEAR TO MONTH;
ds INTERVAL DAY TO SECOND;
newPartName VARCHAR2(30);
PERIOD TIMESTAMP;
BEGIN
FOR aTab IN PartTables LOOP
BEGIN
EXECUTE IMMEDIATE 'BEGIN :ret := '||aTab.INTERVAL||'; END;' USING OUT ds;
ym := NULL;
EXCEPTION
WHEN EXPRESSION_IS_OF_WRONG_TYPE THEN
EXECUTE IMMEDIATE 'BEGIN :ret := '||aTab.INTERVAL||'; END;' USING OUT ym;
ds := NULL;
END;
FOR aPart IN TabParts(aTab.TABLE_NAME) LOOP
EXECUTE IMMEDIATE 'BEGIN :ret := '||aPart.HIGH_VALUE||'; END;' USING OUT PERIOD;
IF ds IS NOT NULL THEN
IF ds >= INTERVAL '7' DAY THEN
-- Weekly partition
EXECUTE IMMEDIATE 'BEGIN :ret := TO_CHAR('||aPart.HIGH_VALUE||' - :int, :fmt); END;' USING OUT newPartName, INTERVAL '1' DAY, '"P_"IYYY"W"IW';
ELSE
-- Daily partition
EXECUTE IMMEDIATE 'BEGIN :ret := TO_CHAR('||aPart.HIGH_VALUE||' - :int, :fmt); END;' USING OUT newPartName, INTERVAL '1' DAY, '"P_"YYYYMMDD';
END IF;
ELSE
IF ym = INTERVAL '3' MONTH THEN
-- Quarterly partition
EXECUTE IMMEDIATE 'BEGIN :ret := TO_CHAR('||aPart.HIGH_VALUE||' - :int, :fmt); END;' USING OUT newPartName, INTERVAL '1' DAY, '"P_"YYYY"Q"Q';
ELSE
-- Monthly partition
EXECUTE IMMEDIATE 'BEGIN :ret := TO_CHAR('||aPart.HIGH_VALUE||' - :int, :fmt); END;' USING OUT newPartName, INTERVAL '1' DAY, '"P_"YYYYMM';
END IF;
END IF;
IF newPartName <> aPart.PARTITION_NAME THEN
EXECUTE IMMEDIATE 'ALTER TABLE '||aTab.TABLE_NAME||' RENAME PARTITION '||aPart.PARTITION_NAME||' TO '||newPartName;
END IF;
END LOOP;
END LOOP;
END MaintainPartitions;
/
CREATE OR REPLACE PROCEDURE rebuild_index
authid current_user
is
BEGIN
for i in (
select index_owner, index_name, partition_name, 'partition' ddl_type
from all_ind_partitions
where status = 'UNUSABLE'
union all
select owner, index_name, null, null
from all_indexes
where status = 'UNUSABLE'
)
loop
if i.ddl_type is null then
ddl('alter index '||i.index_owner||'.'||i.index_name||' rebuild parallel 4 online');
else
ddl('alter index '||i.index_owner||'.'||i.index_name||' modify '||i.ddl_type||' '||i.partition_name||' rebuild parallel 4 online');
end if;
end loop;
END;
/
EXEC MaintainPartitions;
DECLARE
CANNOT_DROP_LAST_PARTITION EXCEPTION;
PRAGMA EXCEPTION_INIT(CANNOT_DROP_LAST_PARTITION, -14758);
CANNOT_DROP_ONLY_ONE_PARTITION EXCEPTION;
PRAGMA EXCEPTION_INIT(CANNOT_DROP_ONLY_ONE_PARTITION, -14083);
ts TIMESTAMP;
CURSOR TablePartitions IS
SELECT TABLE_NAME, PARTITION_NAME, p.HIGH_VALUE, t.INTERVAL, RETENTION, DATA_TYPE
FROM USER_PART_TABLES t
JOIN USER_TAB_PARTITIONS p USING (TABLE_NAME)
JOIN USER_PART_KEY_COLUMNS pk ON pk.NAME = TABLE_NAME
JOIN USER_TAB_COLS tc USING (TABLE_NAME, COLUMN_NAME)
JOIN PARTITION_RETENTION r USING (TABLE_NAME)
WHERE pk.object_type = 'TABLE' AND
t.partitioning_type = 'RANGE' AND
REGEXP_LIKE (tc.data_type, '^DATE$|^TIMESTAMP.*');
BEGIN
FOR aPart IN TablePartitions LOOP
EXECUTE IMMEDIATE 'BEGIN :ret := '||aPart.HIGH_VALUE||'; END;' USING OUT ts;
IF ts < SYSTIMESTAMP - aPart.RETENTION THEN
BEGIN
ddl('alter table '||aPart.TABLE_NAME||' drop partition '||aPart.partition_name);
EXCEPTION
WHEN CANNOT_DROP_ONLY_ONE_PARTITION THEN
DBMS_OUTPUT.PUT_LINE('Cant drop the only partition '||aPart.PARTITION_NAME ||' from table '||aPart.TABLE_NAME);
ddl('ALTER TABLE '||aPart.TABLE_NAME||' TRUNCATE PARTITION '||aPart.PARTITION_NAME);
WHEN CANNOT_DROP_LAST_PARTITION THEN
BEGIN
DBMS_OUTPUT.PUT_LINE('Drop last partition '||aPart.PARTITION_NAME ||' from table '||aPart.TABLE_NAME);
EXECUTE IMMEDIATE 'ALTER TABLE '||aPart.TABLE_NAME||' SET INTERVAL ()';
ddl('alter table '||aPart.TABLE_NAME||' drop partition '||aPart.partition_name);
EXECUTE IMMEDIATE 'ALTER TABLE '||aPart.TABLE_NAME||' SET INTERVAL( '||aPart.INTERVAL||' )';
EXCEPTION
WHEN CANNOT_DROP_ONLY_ONE_PARTITION THEN
-- Depending on the order the "last" partition can be also the "only" partition at the same time
EXECUTE IMMEDIATE 'ALTER TABLE '||aPart.TABLE_NAME||' SET INTERVAL( '||aPart.INTERVAL||' )';
DBMS_OUTPUT.PUT_LINE('Cant drop the only partition '||aPart.PARTITION_NAME ||' from table '||aPart.TABLE_NAME);
ddl('ALTER TABLE '||aPart.TABLE_NAME||' TRUNCATE PARTITION '||aPart.PARTITION_NAME);
END;
END;
END IF;
END LOOP;
rebuild_index();
END;
Use interval partitioning - available starting from Oracle 11.
You will need no procedure for a creation of a partition, because the partition will be created automatically with the first insert of the data with the corresponding date.
You will still need a basic code for drop partition - rolling window is not supported in the interval partitioning.
Using the partition extended names makes it much easier that if you use partition names
Example
Create Interval Partitioned Table
CREATE TABLE test_part
(trans_date DATE,
pad VARCHAR2(100)
)
PARTITION BY RANGE (trans_date)
INTERVAL (NUMTODSINTERVAL(1,'DAY'))
(
PARTITION part_init values LESS THAN (DATE'2020-01-01')
);
Note - use a less than date long in the history for the initial partition so that no data will be inserted there.
This partition will remain empty and will not be dropped, otherwise you encounter
ORA-14083: cannot drop the only partition of a partitioned table.
Create Partition
Now populate that table with few rows.
Note that there is no need for explicite create partition as we use interval partitioning and the partitions are created automatically.
insert into test_part(trans_date, pad)
select add_months(trunc(sysdate),-3)-rownum trans_date, 'X' pad
from dual connect by level <= 3;
Drop Partition
The implenetation of the rolling window consists of two steps
First check the transactions dates that are older than three months
select distinct trunc(trans_date) drop_date from test_part
where trans_date < add_months(trunc(sysdate),-3)
order by 1 desc;
DROP_DATE
-------------------
08.01.2022 00:00:00
07.01.2022 00:00:00
06.01.2022 00:00:00
Now you need to drop partitions for the above selected days.
You can use the *partition extended names to do so, without a need to know the partition name and the ugly LONG HIGH_VALUE.
Example for the day DATE'2022-07-07'
alter table TEST_PART drop partition for (DATE'2022-07-07');
You may pack the clean up logic in a simple procedure
create or replace procedure rolling_window as
v_sql varchar2(4000);
begin
for cur in (
select distinct trunc(trans_date) drop_date from test_part
where trans_date < add_months(trunc(sysdate),-3)
order by 1 desc)
loop
v_sql := q'[alter table TEST_PART drop partition for (DATE']'||
to_char(cur.drop_date,'YYYY-MM-DD')||q'[') ]';
dbms_output.put_line(v_sql);
execute immediate v_sql;
end loop;
end;
/
If you use global indexes you may want to add the clause UPDATE INDEXES in the ALTER TABLEto keep the index usable after the operation.

automatic partition naming for range partitioning

I have a table like this
CREATE TABLE data_audit(
id_col NUMBER(*,0) NOT NULL ENABLE,
col_2 VARCHAR2(10) NOT NULL ENABLE,
col_3 NUMBER(*,0) NOT NULL ENABLE,
col_4 VARCHAR2(10) NOT NULL ENABLE,
col_5 VARCHAR2(10) NOT NULL ENABLE,
created_at TIMESTAMP (3) DEFAULT current_timestamp,
CONSTRAINT DATA_AUDIT_PK PRIMARY KEY (col_2,col_3,col_4)
USING INDEX ENABLE
)
PARTITION BY RANGE(created_at)
(
PARTITION p2022_jan
VALUES LESS THAN (TO_DATE('01-jan-2022')),
PARTITION p2022_feb
VALUES LESS THAN (TO_DATE('01-feb-2022')),
PARTITION p2022_mar
VALUES LESS THAN (TO_DATE('01-mar-2022'))
)
Here - in above example - i need to explicitly mention the name in DDL
I want to create new partition automatically for every month data
How can i achieve it naming it automatically - i am ok with any random name of partition
I am using oracle - Oracle Database 19c Enterprise Edition Release 19.0.0.0
Instead of a RANGE partition I would suggest an INTERVAL partition:
CREATE TABLE DATA_AUDIT (
id_col NUMBER(*,0) NOT NULL ENABLE,
col_2 VARCHAR2(10) NOT NULL ENABLE,
col_3 NUMBER(*,0) NOT NULL ENABLE,
col_4 VARCHAR2(10) NOT NULL ENABLE,
col_5 VARCHAR2(10) NOT NULL ENABLE,
CREATED_AT TIMESTAMP (3) default current_timestamp ,
CONSTRAINT DATA_AUDIT_PK PRIMARY KEY (col_2,col_3,col_4) USING INDEX ENABLE
)
partition by range (CREATED_AT) INTERVAL (INTERVAL '1' MONTH)
(PARTITION p2021_dec VALUES LESS THAN (TIMESTAMP '2022-01-01 00:00:00'));
Then Oracle will create new partition automatically every months.
For renaming you can runs this procedure by daily scheduler job as proposed by Barbaros Özhan.
PROCEDURE RenamePartitions IS
ts TIMESTAMP;
newName VARCHAR2(30);
CURSOR TabPartitions IS
SELECT TABLE_NAME, PARTITION_NAME, HIGH_VALUE
FROM USER_TAB_PARTITIONS
WHERE TABLE_NAME = 'DATA_AUDIT'
ORDER BY 1,2;
BEGIN
EXECUTE IMMEDIATE 'ALTER SESSION SET DDL_LOCK_TIMEOUT = 180';
FOR aPart IN TabPartitions LOOP
EXECUTE IMMEDIATE 'BEGIN :ret := '||aPart.HIGH_VALUE||'; END;' USING OUT ts;
ts := ADD_MONTHS(ts, -1);
newName := 'p'||TO_CHAR(ts,'yyyy_mon', 'NLS_DATE_LANGUAGE = american');
IF aPart.PARTITION_NAME <> newName THEN
EXECUTE IMMEDIATE 'ALTER TABLE '||aPart.TABLE_NAME||' RENAME PARTITION '||aPart.PARTITION_NAME||' TO '||newName;
END IF;
END LOOP;
END RenamePartitions;
Or see a more generic one: Partition table rename automatically in ORACLE
Assume that the table only has the first partition(p2022_jan) and you'll add new partitions to the table every month, then firstly create a stored procedure such as
CREATE OR REPLACE PROCEDURE Pr_Add_Part_to_Data_Audit is
v_ddl VARCHAR2(32767);
v_date DATE := TO_DATE(TO_CHAR(sysdate,'yyyy-mm-')||'01','yyyy-mm-dd');
BEGIN
v_ddl :='ALTER TABLE data_audit ADD PARTITION p'||TO_CHAR(v_date,'yyyy')||'_'||TO_CHAR(v_date,'mon')||' VALUES LESS THAN ('''||v_date||''')';
EXECUTE IMMEDIATE v_ddl;
END;
/
then, call that from a scheduler at the beginning of the upcoming months such as
DECLARE
v_job_name VARCHAR2(32) := 'jb_add_part_data';
BEGIN
DBMS_SCHEDULER.CREATE_JOB(job_name => v_job_name,
job_type => 'STORED_PROCEDURE',
job_action => 'Pr_Add_Part_to_Data_Audit',
start_date => TO_DATE('01-02-2021 01:00:10',
'DD-MM-YYYY HH24:MI:SS'),
repeat_interval => 'FREQ=MONTHLY; BYHOUR=1;',
auto_drop => false,
comments => 'Adds a new partition every month');
DBMS_SCHEDULER.ENABLE(v_job_name);
END;
/
Here the answergiven by Wernfried Domscheit - is correct
thank you for your Answer - it showed the way of controlling partition name - in my case i didn't need to care about partition name - i just needed to make sure - new partition is created with new name - so i used first half of your comment -
to verify it - i used it with DAY - partitioning
CREATE TABLE DATA_AUDIT (
id_col NUMBER(*,0) NOT NULL ENABLE,
col_2 VARCHAR2(10) NOT NULL ENABLE,
col_3 NUMBER(*,0) NOT NULL ENABLE,
col_4 VARCHAR2(10) NOT NULL ENABLE,
col_5 VARCHAR2(10) NOT NULL ENABLE,
CREATED_AT TIMESTAMP (3) default current_timestamp ,
CONSTRAINT DATA_AUDIT_PK PRIMARY KEY (col_2,col_3,col_4) USING INDEX ENABLE
)
partition by range (CREATED_AT) INTERVAL (INTERVAL '1' DAY)
(PARTITION p2021_dec VALUES LESS THAN (TIMESTAMP '2022-01-01 00:00:00'));
and then it created partitions like
partition name - table name
P2021_DEC - DATA_PURGE_AUDIT
SYS_P8592 - DATA_PURGE_AUDIT

PLS-00225: subprogram or cursor 'CHR' reference is out of scope

i make a procedure in plsql it return this error anyone know about it i post my code and error snap shot here
CREATE OR REPLACE PROCEDURE CHR.ATT_INSERT_TEST
IS
CURSOR ATT
IS
SELECT emp.EMPLOYEE_ID EMPLOYEE_ID,
io.CHECKTYPE CHECKTYPE,
io.MACHINE_NUM MACHINE_NUM,
io.ATT_ID ATT_ID,
io.SWIPE_DATE SWIPE_DATE,
io.SWIPE_TIME SWIPE_TIME
FROM INOUT_LIVE_MACHINE_TEST io, CHR_EMGT_EMPLOYEE emp
WHERE emp.EMPLOYEE_CODE = io.EMPLOYEE_CODE
AND io.ATT_ID NOT IN (SELECT ATT_ID_REF
FROM CHR_TA_EMP_SWIPE_IN_OUT
WHERE io.ATT_ID = ATT_ID_REF);
BEGIN
FOR I IN ATT
LOOP
INSERT INTO CHR_TA_EMP_SWIPE_IN_OUT (EMPLOYEE_ID,
SWIPE_DATE,
SWIPE_TIME,
SWIPE_ID,
SWIPE_TYPE,
CREATED_BY,
CREATION_DATE,
CLIENT_IP)
VALUES (I.EMPLOYEE_ID,
TO_DATE (i.SWIPE_DATE, 'MM/DD/YYYY'),
I.SWIPE_TIME,
CHR_TA_SWIPE_IN_OUT_SEQ.NEXTVAL,
I.CHECKTYPE,
I.EMPLOYEE_ID,
TO_DATE (i.SWIPE_DATE, 'MM/DD/YYYY'),
'192.168.0.71'
);
END LOOP;
COMMIT;
END;
/
this is my procedure i make subquery mostly time but this time it return me this kind of error.
i think this error show some issue is regarding alias but i already define alias for each column
i read this artical but my code is still stuck
PLS-00402: alias required in SELECT list of cursor to avoid duplicate column names
this is my table structure
CREATE TABLE CHR.CHR_TA_EMP_SWIPE_IN_OUT
(
EMPLOYEE_ID NUMBER(10) NOT NULL,
SWIPE_DATE DATE NOT NULL,
SWIPE_TIME DATE NOT NULL,
SWIPE_ID NUMBER(10) NOT NULL,
SWIPE_TYPE VARCHAR2(1 BYTE),
CREATED_BY NUMBER(10),
CREATION_DATE DATE,
LAST_UPDATED_BY NUMBER(10),
LAST_UPDATE_DATE DATE,
IS_MANUAL VARCHAR2(1 BYTE),
REASON_LKP NUMBER(10),
CLIENT_IP VARCHAR2(50 BYTE),
IS_REQUESTED VARCHAR2(1 CHAR),
TERMINAL_ID VARCHAR2(50 BYTE),
ATT_ID_REF NUMBER
)
CREATE TABLE CHR.CHR_EMGT_EMPLOYEE
(
EMPLOYEE_ID NUMBER(10) NOT NULL,
EMPLOYEE_CODE VARCHAR2(30 BYTE) NOT NULL
)
CREATE TABLE CHR.INOUT_LIVE_MACHINE_TEST
(
ATT_ID NUMBER,
USERID NUMBER,
EMPLOYEE_CODE NUMBER,
SENSORID NUMBER,
MACHINE_NUM VARCHAR2(20 BYTE),
CHECKTIME VARCHAR2(20 BYTE),
CHECKTYPE VARCHAR2(20 BYTE)
)
Your procedure has no mistakes. Only problem is in your table "INOUT_LIVE_MACHINE_TEST". it has missing SWIPE_DATE & SWIPE_TIME columns. See below the working demo.
Created table with both the columns:
CREATE TABLE INOUT_LIVE_MACHINE_TEST
(
ATT_ID NUMBER,
USERID NUMBER,
EMPLOYEE_CODE NUMBER,
SENSORID NUMBER,
SWIPE_DATE DATE NOT NULL,
SWIPE_TIME DATE NOT NULL,
MACHINE_NUM VARCHAR2(20 BYTE),
CHECKTIME VARCHAR2(20 BYTE),
CHECKTYPE VARCHAR2(20 BYTE)
)
Procedure compiled :
CREATE OR REPLACE PROCEDURE ATT_INSERT_TEST
IS
CURSOR ATT
IS
SELECT emp.EMPLOYEE_ID EMPLOYEE_ID,
io.CHECKTYPE CHECKTYPE,
io.MACHINE_NUM MACHINE_NUM,
io.ATT_ID ATT_ID,
io.SWIPE_DATE SWIPE_DATE,
io.SWIPE_TIME SWIPE_TIME
FROM INOUT_LIVE_MACHINE_TEST io, CHR_EMGT_EMPLOYEE emp
WHERE emp.EMPLOYEE_CODE = io.EMPLOYEE_CODE
AND io.ATT_ID NOT IN (SELECT ATT_ID_REF
FROM CHR_TA_EMP_SWIPE_IN_OUT
WHERE io.ATT_ID = ATT_ID_REF);
BEGIN
FOR I IN ATT
LOOP
INSERT INTO CHR_TA_EMP_SWIPE_IN_OUT (EMPLOYEE_ID,
SWIPE_DATE,
SWIPE_TIME,
SWIPE_ID,
SWIPE_TYPE,
CREATED_BY,
CREATION_DATE,
CLIENT_IP)
VALUES (I.EMPLOYEE_ID,
TO_DATE (i.SWIPE_DATE, 'MM/DD/YYYY'),
I.SWIPE_TIME,
CHR_TA_SWIPE_IN_OUT_SEQ.NEXTVAL,
I.CHECKTYPE,
I.EMPLOYEE_ID,
TO_DATE (i.SWIPE_DATE, 'MM/DD/YYYY'),
'192.168.0.71'
);
END LOOP;
COMMIT;
END;
/

check if multiple records exist in table ORACLE PLSQL

Here I want to check if record exists and based on that I want perform actions.
My code is as below
FOR cell_configs IN (SELECT cc.cell_configuration_name,
cc.cell_configuration_value
from cell_configurations cc
where (cc.cell_configuration_name like height_cc or
cc.cell_configuration_name like width_cc) and
cc.cell_id=c_id)
LOOP
if cc.cell_configuration_name OR
cc.cell_configuration_value EXISTS
then
-- i want to update the table dbms_output.put_line(temp || ' does exist');
else
-- i want to insert records into the table dbms_output.put_line(temp || ' does not exist');
end if;
dbms_output.put_line(c_id || ' ' ||
cell_configs.cell_configuration_name || ' ' ||
cell_configs.cell_configuration_value );
END LOOP;
If there are no records found I can see that I will get empty string i.e ''. I cannot check if it is null or not.
Can anybody help me on this please?.
EDIT (info copied from comments):
I am looking for these 2 rows(height,width) cell_configuration_name like 'container.dealer-content.configs[1].width' or cell_configuration_name like 'container.dealer-content.configs[1].height' cell_configuration_value=flex-width-8 cell_configuration_value=flex-width-250
CELL_CONFIGURATIONS table below
CELL_CONFIGURATION_ID NUMBER(38,0) PK
CELL_ID NUMBER(38,0) FK
CELL_CONFIGURATION_NAME VARCHAR2(100 BYTE)
CELL_CONFIGURATION_VALUE VARCHAR2(4000 BYTE)
IS_LOCKED CHAR(1 BYTE)
MODIFIED_BY VARCHAR2(100 BYTE)
MODIFIED_DATE DATE
CREATED_BY VARCHAR2(100 BYTE)
CREATED_DATE
Sample Data as Below
CELL_ID CELL_CONFIGURATION_NAME CELL_CONFIGURATION_VALUE
37771286880 container.dealer-content.configs[1].height flex-height-2
37771286880 container.dealer-content.configs[1].width flex-width-8
Here is the beggining of a solution...
BEGIN
FOR rec IN
(SELECT cell_id -- assuming that cell_id will repeat for lines with width and height
FROM CELL_CONFIGURATIONS
WHERE CELL_CONFIGURATION_NAME LIKE height_cc
MINUS
SELECT cell_id
FROM CELL_CONFIGURATIONS
WHERE CELL_CONFIGURATION_NAME LIKE width_cc
)
LOOP
-- INSERT STATEMENT
END LOOP;
END;

Resources