Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- DECLARE
- /*
- * Instanciate the variables to run the PL/SQL script
- */
- my_table VARCHAR2(30) := 'abaco'; -- Table name
- my_date DATE := SYSDATE - 10; -- Date
- -- Boolean variable used to store the value checking the table's existence
- table_exists INTEGER;
- /*
- * Procedure to remove old records from a main table and store them in a
- * backup table
- */
- PROCEDURE backup_records_before (table_name VARCHAR2, backup_date DATE) IS
- /*
- * Instanciate the procedure internal variables
- */
- my_query VARCHAR2(300); -- Dynamic SQL query
- table_name_backup VARCHAR(34); -- Name of the backup table
- number_condition NUMBER := 5; -- Backup condition value
- BEGIN
- -- Print out the passed arguments
- DBMS_OUTPUT.PUT_LINE('The table name is:');
- DBMS_OUTPUT.PUT_LINE(table_name);
- DBMS_OUTPUT.PUT_LINE('The backup date is:');
- DBMS_OUTPUT.PUT_LINE(backup_date);
- -- Concat the table name with '_bck' to get the new backup name
- table_name_backup := table_name || '_bck';
- -- Print out the backup table name
- DBMS_OUTPUT.PUT_LINE('The backup table name is:');
- DBMS_OUTPUT.PUT_LINE(table_name_backup);
- -- Create the query to create the backup table and execute it
- my_query := 'CREATE TABLE ' || table_name_backup || ' AS (SELECT * FROM ' || table_name || ' WHERE table_date < ' || backup_date || ')';
- EXECUTE IMMEDIATE my_query;
- -- Print out
- DBMS_OUTPUT.PUT_LINE('Backup table created!');
- END backup_records_before;
- BEGIN
- -- Check the existence of the main table and store the result in table_exists
- SELECT COUNT(*) INTO table_exists FROM USER_TABLES WHERE TABLE_NAME = my_table;
- -- Print out
- DBMS_OUTPUT.PUT_LINE('The main table exists:');
- -- If the main table is not existing
- IF table_exists = 0 THEN
- -- Print out
- DBMS_OUTPUT.PUT_LINE('NO');
- -- Create the table
- EXECUTE IMMEDIATE 'CREATE TABLE ' || my_table || '(table_id NUMBER PRIMARY KEY, table_date DATE)';
- -- Print out
- DBMS_OUTPUT.PUT_LINE('Main table created!');
- -- Fill the table with numbers and dates
- FOR n IN 1 .. 20
- LOOP
- EXECUTE IMMEDIATE 'INSERT INTO ' || my_table || ' (table_id, table_date) VALUES (' || n ||', SYSDATE - '|| n || ')';
- END LOOP;
- END IF;
- -- Print out
- DBMS_OUTPUT.PUT_LINE('YES');
- -- Remove the old records from the created table
- backup_records_before (my_table, my_date);
- END;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement