Scripted Conversion of Views to Materialized Views (Oracle) - sql

We have certain environments that prefer the use of materialized views, but the regular applications use regular views. To make things easier we want our application to automatically migrate all the regular views to materialized views in an automated fashion, based upon a configuration parameter.
I've written what I consider to be the most of what I need to get this script working, but I am struggling on the final touches. Possibly there are some escaping issues that I need to work around too.
For now the script creates a view called 'magic' and then tries to convert that, but so far it's not working on the conversion to a materialized view stage. I am unsure what I've done wrong. Any help greatly appreciated.
The error I am seeing is as follows.
Error report:
ORA-00911: invalid character
ORA-06512: at line 49
ORA-00911: invalid character
00911. 00000 - "invalid character"
*Cause: identifiers may not start with any ASCII character other than
letters and numbers. $#_ are also allowed after the first
character. Identifiers enclosed by doublequotes may contain
any character other than a doublequote. Alternative quotes
(q'#...#') cannot use spaces, tabs, or carriage returns as
delimiters. For all other contexts, consult the SQL Language
Reference Manual.
*Action:
Attempting to drop materialized view named MAGIC
No materialized view found with name MAGIC
Attempting to drop view named MAGIC
Success.
Attempting to create materialized view named MAGIC
CREATE MATERIALIZED VIEW "MYDB"."MAGIC" ("MAGIC") AS
SELECT 'MAGIC' FROM DUAL;
Failed to create materialized view, recreating original view MAGIC
ERROR: Could not recreate view named MAGIC.
SQL was:
CREATE OR REPLACE FORCE VIEW "MYDB"."MAGIC" ("MAGIC") AS
SELECT 'MAGIC' FROM DUAL;
The PL/SQL code is below.
clear;
SET serveroutput ON size 1000000;
/**
* Converts all views in the database to materialized views.
*/
CREATE OR REPLACE VIEW "MAGIC" ("MAGIC") AS SELECT 'MAGIC' FROM DUAL;
BEGIN
FOR cur_rec IN ( SELECT object_name, object_type FROM user_objects WHERE object_type='VIEW' and object_name='MAGIC' )
LOOP
BEGIN
FOR cur_view IN
(SELECT TRIM( REPLACE( REPLACE( DBMS_METADATA.GET_DDL('VIEW', cur_rec.object_name), 'CREATE OR REPLACE FORCE VIEW', 'CREATE MATERIALIZED VIEW' ), 'CREATE OR REPLACE VIEW', 'CREATE MATERIALIZED VIEW' ) ) "MATERIALIZED_VIEW",
TRIM( DBMS_METADATA.GET_DDL('VIEW', cur_rec.object_name) ) "VIEW"
FROM DUAL
)
LOOP
BEGIN
BEGIN
DBMS_OUTPUT.PUT_LINE( 'Attempting to drop materialized view named ' || cur_rec.object_name );
EXECUTE IMMEDIATE 'drop materialized view ' || cur_rec.object_name;
DBMS_OUTPUT.PUT_LINE( 'Success.' );
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE( 'No materialized view found with name ' || cur_rec.object_name );
IF SQLCODE != -12003 THEN
RAISE;
END IF;
END;
BEGIN
DBMS_OUTPUT.PUT_LINE( 'Attempting to drop view named ' || cur_rec.object_name );
EXECUTE IMMEDIATE 'drop view ' || cur_rec.object_name;
DBMS_OUTPUT.PUT_LINE( 'Success.' );
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE( 'No view found with name ' || cur_rec.object_name );
IF SQLCODE != -942 THEN
RAISE;
END IF;
END;
-- create the view as a materialized view.
BEGIN
DBMS_OUTPUT.PUT_LINE( 'Attempting to create materialized view named ' || cur_rec.object_name );
DBMS_OUTPUT.PUT_LINE( cur_view."MATERIALIZED_VIEW" );
EXECUTE IMMEDIATE cur_view."MATERIALIZED_VIEW";
DBMS_OUTPUT.PUT_LINE( 'Success.' );
EXCEPTION
WHEN OTHERS THEN
BEGIN
DBMS_OUTPUT.PUT_LINE( 'Failed to create materialized view, recreating original view ' || cur_rec.object_name );
EXECUTE IMMEDIATE cur_view."VIEW";
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE( 'ERROR: Could not recreate view named ' || cur_rec.object_name || '.' );
DBMS_OUTPUT.PUT_LINE( 'SQL was:' || cur_view."VIEW" );
RAISE;
END;
END;
END;
END LOOP;
END;
END LOOP;
END;

The problem is with the SQL it's trying to execute:
CREATE MATERIALIZED VIEW "MYDB"."MAGIC" ("MAGIC") AS
SELECT 'MAGIC' FROM DUAL;
The dynamic SQL should be a single statement and cannot have a statement terminator/separator; it's the final ; it doesn't like.
You can stop dbms_metadata including it in the DDL in the first place by adding a call to the set_transform_param() procedure in your block, before you call get_ddl():
dbms_metadata.set_transform_param(dbms_metadata.session_transform,
'SQLTERMINATOR', false);

UPDATE - Final Solution
The database was crashing server-side when running this script as some of my views depend on others. I get the impression that this is done in a multi-threaded fashion and that caused the server to crash and burn as views were in various states of readiness. From a sequential processing point of view, I can't see how this can fail. The dependant views exist either as a materialized view or a regular view.
Finally, it's possible these times could be reduced, these were the values that worked for me, but I've not tested lower thresholds at the time of writing this answer.
set serveroutput on size 1000000;
/**
* Converts all views in the database to materialized views.
*/
begin
dbms_metadata.set_transform_param(dbms_metadata.session_transform, 'SQLTERMINATOR', false );
for cur_rec in ( SELECT object_name, object_type from user_objects where object_type='VIEW' )
loop
begin
for cur_view in
(select trim( replace( replace( dbms_metadata.get_ddl( 'VIEW', cur_rec.object_name ), 'CREATE OR REPLACE FORCE VIEW', 'CREATE MATERIALIZED VIEW' ), 'CREATE OR REPLACE VIEW', 'CREATE MATERIALIZED VIEW' ) ) "MATERIALIZED_VIEW",
trim( dbms_metadata.get_ddl( 'VIEW', cur_rec.object_name ) ) "VIEW"
from dual )
loop
begin
begin
execute immediate 'drop materialized view ' || cur_rec.object_name;
dbms_lock.sleep(5);
exception
when others then
if sqlcode != -12003 then
raise;
end if;
end;
begin
execute immediate 'drop view ' || cur_rec.object_name;
dbms_lock.sleep(5);
exception
when others then
if sqlcode != -942 then
raise;
end if;
end;
-- create the view as a materialized view.
begin
dbms_output.put_line( 'Attempting to create materialized view named ' || cur_rec.object_name );
execute immediate cur_view."MATERIALIZED_VIEW";
dbms_lock.sleep(5);
exception
when others then
begin
dbms_output.put_line( 'Failed to create materialized view, recreating original view ' || cur_rec.object_name );
dbms_output.put_line( 'Error was: ' || sqlerrm( sqlcode ) );
dbms_output.put_line( cur_view."MATERIALIZED_VIEW" );
execute immediate cur_view."VIEW";
dbms_lock.sleep(5);
exception
when others then
dbms_output.put_line( 'ERROR: Could not recreate view named ' || cur_rec.object_name || '.' );
dbms_output.put_line( 'SQL was:' || cur_view."VIEW" );
raise;
end;
end;
end;
end loop;
end;
end loop;
end;

Related

multiple drop trigger statements not working

The below PL/SQL is not working as expected
The ask is to delete triggers if it exists. The below is deleting only the first trigger.
BEGIN
EXECUTE IMMEDIATE 'DROP TRIGGER ' || 'trigger1';
EXECUTE IMMEDIATE 'DROP TRIGGER ' || 'trigger2';
EXECUTE IMMEDIATE 'DROP TRIGGER ' || 'trigger3';
EXCEPTION
WHEN OTHERS THEN
IF SQLCODE != -4080 THEN
RAISE;
END IF;
END;
If the first or second trigger doesn't exist then you'll drop to the exception handler. It won't then return to the original program flow, even when you ignore the error, and it will never see or attempt the later dynamic calls.
You need an exception handler around each individual drop.
To reduce repetition you could do that in a loop, or with a local procedure:
DECLARE
PROCEDURE drop_trigger(p_trigger_name user_triggers.trigger_name%type) IS
BEGIN
EXECUTE IMMEDIATE 'DROP TRIGGER ' || p_trigger_name;
EXCEPTION
WHEN OTHERS THEN
IF SQLCODE != -4080 THEN
RAISE;
END IF;
END drop_trigger;
BEGIN
drop_trigger('trigger1');
drop_trigger('trigger2');
drop_trigger('trigger3');
END;
/
db<>fiddle
You can also add debugging, with dbms_output, to see what's happening - as in this modified db<>fiddle.

He does not perform the procedure. Fail in first step. Oracle

I created procedure in oracle that drops my table and creates same table from my view. But I have some problems with running this procedure. First step with drop table works but copying it doesn't work.
It this a good procedure ?
create or replace PROCEDURE transfer_table (table_name IN VARCHAR2,tableFrom IN VARCHAR2) IS
BEGIN
EXECUTE IMMEDIATE 'DROP TABLE ' || table_name;
EXECUTE IMMEDIATE 'CREATE TABLE ' || table_name || ' AS SELECT * FROM ' || tableFrom;
commit;
END transfer_table;
Next I click on this procedure and change the variable then view and click ok, but only the first step of dropping the table is working. What am I doing wrong ?
I think you need to catch the error if the table you are creating doesn't exist.
create or replace PROCEDURE transfer_table (table_name IN VARCHAR2,tableFrom IN VARCHAR2) IS
BEGIN
BEGIN
EXECUTE IMMEDIATE 'DROP TABLE ' || table_name;
EXCEPTION WHEN OTHERS THEN
NULL;
END;
EXECUTE IMMEDIATE 'CREATE TABLE ' || table_name || ' AS SELECT * FROM ' || tableFrom;
commit;
END transfer_table;

Drop table having name: <table_name>_(sysdate-1) only if the table exist

I need to drop a table only if the table exist, can do it using plsql block
BEGIN
EXECUTE IMMEDIATE 'DROP TABLE <table_name>;
EXCEPTION
WHEN OTHERS THEN
IF SQLCODE != -942 THEN
RAISE;
END IF;
END
But in my case the table name has sysdate (02062017) eg table001_02072017 and i need to delete all such tables with sysdate-1.
How can i do so?
You can find the table with the given pattern from user_tables dictionary table and loop on the result to drop each one by one.
begin
for t in (select table_name from user_tables
where table_name like '%\_'||to_char(sysdate-1,'mmddyyyy') escape '\')
loop
execute immediate 'drop table ' || t.table_name;
end loop;
exception
/* Handle your exceptions here. */
end;
/
Using WHEN OTHERS in your exception handling is discouraged. You should explicitly handle the errors.
Dynamic sql will help you here just use
execute immediate 'drop table ' || table_name;
inside your procedure

Drop Table Exception Intermittently doesn't work

I have been wrapping my "drop tables" in the following block to avoid raising 942 errors if the table doesn't exist:
BEGIN
EXECUTE IMMEDIATE 'DROP TABLE MY_TABLE1';
EXECUTE IMMEDIATE 'DROP TABLE MY_TABLE2';
EXECUTE IMMEDIATE 'DROP TABLE MY_TABLE3';
EXECUTE IMMEDIATE 'DROP TABLE MY_TABLE4';
EXECUTE IMMEDIATE 'DROP TABLE MY_TABLE5';
EXECUTE IMMEDIATE 'DROP TABLE MY_TABLE6';
EXCEPTION
WHEN OTHERS THEN
IF SQLCODE != -942 THEN RAISE;
END IF;
END;
This works great most of the of time. However, intermittently it will seem to refuse to drop this table or that. It's not always the same table, and it doesn't always happen in any particular set of queries. It just happens...sometimes...for reasons I can't explain, hence my asking this question.
Has anyone else experienced this, and if so, what did you do about it?
Most likely cause I can think of is the table is locked (outstanding commits) in another session. What error is reported?
Also there is a problem with your script - if TABLE1 has already been dropped, TABLE2...6 won't get dropped because your first DROP will jump to the exception.
Better to do this:
DECLARE
PROCEDURE drp ( tName IN VARCHAR2 ) IS
BEGIN
EXECUTE IMMEDIATE 'drop table ' || tName;
EXCEPTION
WHEN OTHERS THEN
IF SQLCODE != -942 THEN RAISE;
END IF;
END;
BEGIN
drp ( 'TABLE1' );
drp ( 'TABLE2' );
drp ( 'TABLE3' );
-- etc
END;

Oracle 11g: ORA-00604: error occurred at recursive SQL level 1

I executed the script below and it works:
BEGIN
FOR cur_rec IN (SELECT object_name, object_type
FROM user_objects
WHERE object_type IN
('TABLE',
'VIEW',
'PACKAGE',
'PROCEDURE',
'FUNCTION',
'SEQUENCE'
))
LOOP
BEGIN
IF cur_rec.object_type = 'TABLE'
THEN
EXECUTE IMMEDIATE 'DROP '
|| cur_rec.object_type
|| ' "'
|| cur_rec.object_name
|| '" CASCADE CONSTRAINTS';
ELSE
EXECUTE IMMEDIATE 'DROP '
|| cur_rec.object_type
|| ' "'
|| cur_rec.object_name
|| '"';
END IF;
EXCEPTION
WHEN OTHERS
THEN
DBMS_OUTPUT.put_line ( 'FAILED: DROP '
|| cur_rec.object_type
|| ' "'
|| cur_rec.object_name
|| '"'
);
END;
END LOOP;
END;
/
But the problem is, after this, I cant grant, create or drop etc. in my database even I'm using a sysdba user.
I am getting the error:
ORA-00604: error occurred at recursive SQL level 1
ORA-00942: table or view does not exist
Please help. Thanks.
One possible cause for the recursive SQL error is triggers. You might have run into this scenario:
you have a trigger that fires for every DDL statement
this trigger tries to insert records into some kind of audit/log table
you audit/log table was dropped by your cleanup script
To get a list of all triggers, you can use
select * from dba_triggers
where trigger_type not in ('BEFORE EACH ROW','AFTER EACH ROW')
(you can exclude row-level triggers because they conceptually belong to the table and would have been automatically dropped when you dropped the table). After you've identified the offending trigger, you can either disable or drop it.