Received: from megazone.bigpanda.com (megazone.bigpanda.com [63.150.15.178]) by postgresql.org (8.11.3/8.11.4) with ESMTP id fBALrxm35116 for ; Mon, 10 Dec 2001 16:54:03 -0500 (EST) (envelope-from sszabo@megazone23.bigpanda.com) Received: by megazone.bigpanda.com (Postfix, from userid 1001) id DA176D5E9; Mon, 10 Dec 2001 13:54:00 -0800 (PST) Received: from localhost (localhost [127.0.0.1]) by megazone.bigpanda.com (Postfix) with ESMTP id CFC9A5BEE; Mon, 10 Dec 2001 13:54:00 -0800 (PST) Date: Mon, 10 Dec 2001 13:54:00 -0800 (PST) From: Stephan Szabo To: "=?utf-8?Q?darthxiong@libero.it?=" Cc: Subject: Re: =?iso-8859-1?Q?table_name_as_parameter_in_pl/psql?= In-Reply-To: Message-ID: <20011210134736.D70079-100000@megazone23.bigpanda.com> MIME-Version: 1.0 Content-Type: TEXT/PLAIN; charset=US-ASCII X-Archive-Number: 200112/68 X-Sequence-Number: 2792 On Mon, 10 Dec 2001, [utf-8] darthxiong@libero.it wrote: > > hi all, i'm trying to do something like this: > > CREATE FUNCTION read_table(text) RETURNS int AS ' > DECLARE > table_name ALIAS FOR $1; > res > INTERGER; > BEGIN > SELECT INTO res COUNT(id) FROM table_name; > RETURN res; > END; > ' LANGUAGE 'plpgsql'; > > using psql the creation return no errors, but the statement > SELECT read_table( 'books' ) AS how_many; > resuts in > ERROR: parser: parse error at or near "$1" > > and the same using > SELECT INTO res COUNT(id) FROM $1; > instead of > SELECT INTO res COUNT(id) FROM table_name; > while > SELECT INTO res COUNT(id) FROM books ( the real name of the table ) > works good You need to look into using EXECUTE if you want to specify tables on the fly, and you may need something like: create function read_table(text) returns int as ' declare table_name alias for $1; rec record; begin for rec in EXECUTE ''select count(*) from '' || table_name LOOP return rec.count; END LOOP; return 0; end;' language 'plpgsql';