create or replace procedure tmp_proc_view() as $$ declare row record; begin drop table if exists tmp_ddlDef; create table tmp_ddlDef( schemaname varchar,tablename varchar, "DDL" varchar(max)); for row in SELECT n.nspname AS schemaname ,c.relname AS viewname ,'--DROP ' || CASE STRPOS(LOWER(pg_get_viewdef(c.oid, TRUE)), 'materialized') WHEN 8 THEN 'MATERIALIZED '::text --CREATE MATERIALIZED would be the start ELSE ''::text END || 'VIEW ' + QUOTE_IDENT(n.nspname) + '.' + QUOTE_IDENT(c.relname) + ';\n' + CASE STRPOS(LOWER(pg_get_viewdef(c.oid, TRUE)), 'create') WHEN 1 then '' -- CREATE statement already present ELSE --no CREATE statement present so no materialized view anyway 'CREATE OR REPLACE VIEW ' + QUOTE_IDENT(n.nspname) + '.' + QUOTE_IDENT(c.relname) + ' AS\n' END || COALESCE(pg_get_viewdef(c.oid, TRUE), '') AS ddl FROM pg_catalog.pg_class AS c INNER JOIN pg_catalog.pg_namespace AS n ON c.relnamespace = n.oid WHERE relkind = 'v' and schemaname not in ('information_schema', 'pg_catalog') loop insert into tmp_ddlDef(schemaname,tablename,ddl) values (row.schemaname,row.viewname,row.ddl); end loop ; end; $$ language plpgsql ;