Received: from localhost (postgresql.org [64.49.215.8]) by postgresql.org (Postfix) with ESMTP id 0E96E47610B for ; Thu, 16 Jan 2003 23:44:46 -0500 (EST) Received: from megazone.bigpanda.com (megazone.bigpanda.com [63.150.15.178]) by postgresql.org (Postfix) with ESMTP id D13AA47644C for ; Thu, 16 Jan 2003 23:43:44 -0500 (EST) Received: by megazone.bigpanda.com (Postfix, from userid 1001) id C522FD602; Thu, 16 Jan 2003 20:43:49 -0800 (PST) Received: from localhost (localhost [127.0.0.1]) by megazone.bigpanda.com (Postfix) with ESMTP id B6CC75C03; Thu, 16 Jan 2003 20:43:49 -0800 (PST) Date: Thu, 16 Jan 2003 20:43:49 -0800 (PST) From: Stephan Szabo To: Matthew Nuzum Cc: Subject: Re: cannot create function that uses variable table name In-Reply-To: <001d01c2bdd9$191b07f0$6700a8c0@mattspc> Message-ID: <20030116204152.I15804-100000@megazone23.bigpanda.com> MIME-Version: 1.0 Content-Type: TEXT/PLAIN; charset=X-UNKNOWN Content-Transfer-Encoding: QUOTED-PRINTABLE X-Virus-Scanned: by AMaViS new-20020517 X-Archive-Number: 200301/273 X-Sequence-Number: 11138 On Thu, 16 Jan 2003, Matthew Nuzum wrote: > I have a number of tables in my database that use the concept of > =93display order=94, which is a field that can be used in an order by cla= use > to dictate what order the results should come out in. > =A0 > I thought I would be crafty and devise a function that would always > return the highest numbered item in the table. But it doesn=92t work. It > always gives me a parse error at $1. Here=92s the function: > > CREATE OR REPLACE FUNCTION get_last_dsply_order( > varchar, -- tablename > varchar, -- id_col_name > varchar) -- where_item > RETURNS integer AS ' > DECLARE total_items integer; > tablename ALIAS FOR $1; > id_col_name ALIAS FOR $2; > where_item ALIAS FOR $3; > BEGIN > SELECT INTO total_items count(*) FROM tablename WHERE id_col_name > =3D where_item; > RETURN total_items; > END; > ' LANGUAGE 'plpgsql'; You'll need to look into EXECUTE. You also are going to have to watch out for concurrency issues since two transactions calling this function at the same time for the same args are likely to give incorrect results.