X-Original-To: pgsql-sql-postgresql.org@localhost.postgresql.org Received: from localhost (unknown [200.46.204.144]) by svr1.postgresql.org (Postfix) with ESMTP id 5E19E329EA8 for ; Tue, 21 Sep 2004 16:25:55 +0100 (BST) Received: from svr1.postgresql.org ([200.46.204.71]) by localhost (av.hub.org [200.46.204.144]) (amavisd-new, port 10024) with ESMTP id 65359-04 for ; Tue, 21 Sep 2004 15:25:46 +0000 (GMT) Received: from megazone.bigpanda.com (megazone.bigpanda.com [64.147.171.210]) by svr1.postgresql.org (Postfix) with ESMTP id 41EB7329E90 for ; Tue, 21 Sep 2004 16:25:45 +0100 (BST) Received: by megazone.bigpanda.com (Postfix, from userid 1001) id 6E04B3554D; Tue, 21 Sep 2004 08:25:44 -0700 (PDT) Received: from localhost (localhost [127.0.0.1]) by megazone.bigpanda.com (Postfix) with ESMTP id 6C9AC35510; Tue, 21 Sep 2004 08:25:44 -0700 (PDT) Date: Tue, 21 Sep 2004 08:25:44 -0700 (PDT) From: Stephan Szabo To: CHRIS HOOVER Cc: pgsql-sql@postgresql.org Subject: Re: Help with function In-Reply-To: Message-ID: <20040921082228.O11758@megazone.bigpanda.com> References: MIME-Version: 1.0 Content-Type: TEXT/PLAIN; charset=US-ASCII X-Virus-Scanned: by amavisd-new at hub.org X-Spam-Status: No, hits=0.0 tagged_above=0.0 required=5.0 tests= X-Spam-Level: X-Archive-Number: 200409/190 X-Sequence-Number: 19036 On Tue, 21 Sep 2004, CHRIS HOOVER wrote: > Thanks a bunch for the pointers and help. > > One other hopefully quick question. > > How do you query using a variable containing the query? > > I'm trying to build a select statment based upon what parameters are being > passed to the function. > > somthing like this: > > Declare > Param1 varchar; > Param2 varchar; > SQLStr varchar; > Table_rec Table%ROWTYPE; > Begin > > SQLStr:="select * from table" > Param1:= $1; > Param2 :=$2; > > if (Param1 is not null) then > SQLStr := SQLStr || "where column=Param1"; > else > SQLStr := SQLStr || "where column=Param2"; > end if; > SQLStr := SQLStr || ";" > > for Table_Rec in SQLStr loop > return next Table_rec; > end loop; > return; > > end; > > Is this possible? Pretty much yes. You can use the FOR IN EXECUTE LOOP structure to run the query. The only thing is that you have to put the values into the string not the name of the parameters (probably using quote_literal). So rather than SQLStr := SQLStr || "where column = Param1"; you'd want something like: SQLStr := SQLStr || "where column = " || quote_literal(Param1);