pg.ddx.io  pgsql-sql@postgresql.org mailing list archive  
help / color / mirror / Atom feed
From: Stephan Szabo <sszabo@megazone.bigpanda.com>
To: CHRIS HOOVER <CHRIS.HOOVER@companiongroup.com>
Cc: pgsql-sql@postgresql.org
Subject: Re: Help with function
Date: Tue, 21 Sep 2004 08:25:44 -0700 (PDT)
Message-ID: <20040921082228.O11758@megazone.bigpanda.com> (raw)
In-Reply-To: <NZb07058-646270b1@companiongroup.com>
References: <NZb07058-646270b1@companiongroup.com>

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 <record> IN EXECUTE <sqlstring> 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);



view thread (7+ messages)  latest in thread

Message-ID: <20040921082228.O11758@megazone.bigpanda.com>
Permalink:  ../20040921082228.O11758@megazone.bigpanda.com/
Also on:    postgresql.org/message-id/20040921082228.O11758@megazone.bigpanda.com

 · 

reply

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Reply to all the recipients using the --to and --cc options:
  reply via email

  To: pgsql-sql@postgresql.org
  Cc: sszabo@megazone.bigpanda.com, CHRIS.HOOVER@companiongroup.com
  Subject: Re: Help with function
  In-Reply-To: <20040921082228.O11758@megazone.bigpanda.com>

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox