Oracle Drop and Recreate Existing Materialized View

Couldn’t find a script online that appropriately dropped and recreated an MV. We had an issue using impdp on 11g R1 where the MVs were imported under the right schema user, but for some reason, we couldn’t refresh the MV. The solution was to drop and recreate the MVs.


-- Drop and recreate MV for the current schema owner by Theo Chakkapark (http://suteki.nu)
DECLARE
	v_sql varchar2(32767);
 	TYPE mv_tables IS TABLE OF dba_mviews%rowtype INDEX BY PLS_INTEGER;

	mvrows mv_tables;
BEGIN

    	SELECT * BULK COLLECT INTO mvrows FROM user_mviews;
	
	IF(mvrows.count  0) THEN
	  FOR i IN mvrows.FIRST .. mvrows.LAST
	  LOOP
      v_sql := 'DROP MATERIALIZED VIEW ' || mvrows(i).owner || '.' || mvrows(i).mview_name;
      execute immediate (v_sql);
      dbms_output.put_line(v_sql);
      v_sql := 'CREATE MATERIALIZED VIEW ' || mvrows(i).owner || '.' || mvrows(i).mview_name || ' 
BUILD IMMEDIATE REFRESH COMPLETE AS ' || mvrows(i).query;
      execute immediate (v_sql);	  
      dbms_output.put_line(v_sql);		
      END LOOP;
	END IF;

END;
/


About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s