Thread: CREATE VIEW (dynamically)

CREATE VIEW (dynamically)

From
Emmanuel Engelhart
Date:
code
<<
CREATE FUNCTION "requests_insert_after" () RETURNS opaque AS '
DECLAREview_name    text;
BEGINview_name := ''request_'' || NEW.id;CREATE VIEW view_name AS select * from groups;return NEW;
END' LANGUAGE 'plpgsql';

CREATE TRIGGER "requests_insert_after" AFTER INSERT ON "requests"  FOR EACH ROW
EXECUTE PROCEDURE "requests_insert_after" ();>>

This code after an insertion on table "requests" give me this message :
<<
PostgreSQL said: ERROR: parser: parse error at or near "$1" 
>>

Why ?

Thx for any help.

Emmanuel Engelhart


Re: CREATE VIEW (dynamically)

From
Christoph Haller
Date:
> CREATE FUNCTION "requests_insert_after" () RETURNS opaque AS '
> DECLARE
>       view_name       text;
> BEGIN
>       view_name := ''request_'' || NEW.id;
>       CREATE VIEW view_name AS select * from groups;
>       return NEW;
> END' LANGUAGE 'plpgsql';
>
> CREATE TRIGGER "requests_insert_after" AFTER INSERT ON "requests"  FOR
EACH ROW
> EXECUTE PROCEDURE "requests_insert_after" ();>>
>
> This code after an insertion on table "requests" give me this message
:
> <<
> PostgreSQL said: ERROR: parser: parse error at or near "$1"
> >>
>
> Why ?
>
You should check the documentation of plpgsql for the section
Executing dynamic queries (which also means commands like update, etc.)

e.g. to drop a view within plpgsql you have to code
 EXECUTE ''DROP VIEW '' || quote_ident( view_name) ;

Regards, Christoph