Re: plpgsql syntax error

From: Adrian Klaver <adrian(dot)klaver(at)gmail(dot)com>
To: pgsql-general(at)postgresql(dot)org
Cc: József Kurucz <jozsef(dot)kurucz(at)invitel(dot)hu>
Subject: Re: plpgsql syntax error
Date: 2011-10-10 13:44:45
Message-ID: 201110100644.45703.adrian.klaver@gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On Monday, October 10, 2011 3:35:27 am József Kurucz wrote:
> Hi,
>
> I'm beginner in postgresql and plpgsql and i have the following problem.
> I'm trying to check a table if exists or not and when not exists then
> create it, but I get a syntax error.
>
> Here is my code:
>
>
> create or replace function check_table() returns void as
> $$
>
> DECLARE
>
> mmonth integer;
> yyear integer;
>
> tblname varchar(30);
>
> begin
>
> SELECT into mmonth EXTRACT(MONTH FROM TIMESTAMP 'now' - INTERVAL '1
> MONTH'); SELECT into yyear EXTRACT(YEAR FROM TIMESTAMP 'now' - INTERVAL '1
> MONTH');
>
> tblname := 'tbl_' || yyear || mmonth;
>
>
> if not exists(select * from information_schema.tables
> where
> table_catalog = CURRENT_CATALOG and table_schema =
> CURRENT_SCHEMA and table_name = tblname) then
>
> create table tblname
> (
>
> );
>
> end if;
>
> end;
> $$
> language 'plpgsql';
>
>
>
> But I get the following error:
>
> ERROR: syntax error at or near "$1"
> LINE 1: create table $1 ( )
> ^
> QUERY: create table $1 ( )
> CONTEXT: SQL statement in PL/PgSQL function "check_table" near line 22

I ran the function here and did not receive a syntax error. The problem though,
was it created a table named tblname. To get it to work as designed I
substituted :

create table tblname
(

);

with:

EXECUTE 'create table ' || tblname || '()';


> Thanks!

--
Adrian Klaver
adrian(dot)klaver(at)gmail(dot)com

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Jack Christensen 2011-10-10 14:05:06 Re: Failure controlling PG 9.1 service on Ubuntu 10.04 32-bit
Previous Message Adarsh Sharma 2011-10-10 13:32:26 Re: Select latest Timestamp values with group by