LKBEN11157: Howto use variables in the tables with pl/pgsql and postgres


Symptom

You want to create variable table or function names in postgresql

Cause

none

Solution

In the case of executing dynamic sql commands, you can use the execute command in pl/pgsql.

e.g.

CREATE  FUNCTION somefunction(name varchar, language varchar)
  RETURNS void AS
$BODY$
DECLARE
    table_cmd;     --the command that we build to execute
    tablename    text;
BEGIN

    tablename := $1 || 'suffix'; --naming convention
    
    table_cmd :=     'create table ' ||  tablename
            || ' ( ' || primkey || ' serial unique,'
            || 'Title        varchar(255) not null,'
            || 'Symptom        varchar(1500) not null,'
            || 'Cause        varchar(1500) default ''the'');'

    raise notice 'table_cmd is %', table_cmd; --show some information when run
    --EXECUTE table_cmd; --comment this out to create the table

END;
$BODY$
  LANGUAGE 'plpgsql' VOLATILE;

Disclaimer:

The information provided in this document is intended for your information only. Lubby makes no claims to the validity of this information. Use of this information is at own risk!

About the Author

Author: Wim Peeters - Keskon GmbH & Co. KG

Wim Peeters is electronics engineer with an additional master in IT and over 30 years of experience, including time spent in support, development, consulting, training and database administration. Wim has worked with SQL Server since version 6.5. He has developed in C/C++, Java and C# on Windows and Linux. He writes knowledge base articles to solve IT problems and publishes them on the Lubby Knowledge Platform.