Обсуждение: functions with plpgsql
Hi,
I have some problems by using functions with plpgsql.
For example:
tbl:
CREATE TABLE "logs" (
"id" int4 DEFAULT nextval('"logs_id_seq"'::text) NOT NULL,
"session" varchar NOT NULL,
"addr" inet NOT NULL,
"host" varchar NOT NULL,
"agent" varchar NOT NULL,
"datum" timestamptz DEFAULT now(),
"referer" varchar,
CONSTRAINT "logs_pkey" PRIMARY KEY ("id")
);
function:
CREATE FUNCTION "next_id"(character varying) RETURNS integer AS '
DECLARE
tabelle ALIAS FOR $1;
BEGIN
SELECT MAX(id)+1 FROM tabelle;
END;
' LANGUAGE 'plpgsql'
query:
SELECT next_id(logs);
error:
PostgreSQL meldet: ERROR: parser: parse error at or near "$1"
Can anybody help me?
MfG
Bernd Hoffmann
unixserver.info
96123 Litzendorf
Tel: +499505/8050485
Fax: +499505/8050486
info@unixserver.info
> CREATE FUNCTION "next_id"(character varying) RETURNS integer AS ' > DECLARE > tabelle ALIAS FOR $1; > BEGIN > SELECT MAX(id)+1 FROM tabelle; > END; > ' LANGUAGE 'plpgsql' > > query: > > SELECT next_id(logs); > > error: > > PostgreSQL meldet: ERROR: parser: parse error at or near "$1" > > Can anybody help me? I do not think you can evaluate a declared vairable as a table name in the SELECT statement. I don't think you really need to do this though. If you have the table name already. why go: SELECT next_id(logs); And write this functios instead of: SELECT MAX(id) + 1 FROM logs; ?? Andy
Hallo Andy, > I do not think you can evaluate a declared vairable as a table name in the > SELECT statement. where can I find some docu about declare a table by variable. > I don't think you really need to do this though. If you have the table name > already. > why go: > SELECT next_id(logs); > SELECT MAX(id) + 1 FROM logs; it's only a example, I got everytime the error: PostgreSQL meldet: ERROR: parser: parse error at or near "$1" PS.: Excuse me, for my bad english :) MfG Bernd
Bernd Hoffmann wrote: > Hallo Andy, > > >>I do not think you can evaluate a declared vairable as a table name in the >>SELECT statement. > > > where can I find some docu about declare a table by variable. you need to do this as a dynamic query. look in the pl/pgsql docs here http://www.postgresql.org/docs/7.3/interactive/plpgsql-statements.html and here http://www.postgresql.org/docs/7.3/interactive/plpgsql-control-structures.html for description of the FOR-IN-EXECUTE loop you need for dynamic SELECTs basically it'll be something like FOR myrecordvar IN EXECUTE ''select max(id) from '' || quote_ident(mytablenamevar) LOOP ... do some stuff ... END LOOP;