Re: Referencing function value inside CASE..WHEN

From: Martijn van Oosterhout <kleptog(at)svana(dot)org>
To: lover boi <lover-boi(at)live(dot)co(dot)uk>
Cc: pgsql-general(at)postgresql(dot)org
Subject: Re: Referencing function value inside CASE..WHEN
Date: 2011-06-19 10:29:45
Message-ID: 20110619102944.GB3197@svana.org
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On Sun, Jun 19, 2011 at 10:45:12AM +0800, lover boi wrote:
> In the following statement, does the custom function get executed twice?
>
> SELECT
> MY_FUNCTION(...),
> CASE WHEN MY_FUNCTION(...) = '...' THEN '...' ELSE '...' END

Yes

> If so, is there a way I can make it execute once? I tried this but it gave me a "Column my_function does not exist" error.
>
> SELECT
>
> MY_FUNCTION(...) AS my_function,
>
> CASE WHEN my_function = '...' THEN '...' ELSE '...' END

You almost had it right, there is another syntax for CASE:

CASE MY_FUNCTION(...) WHEN 'foo' THEN ... WHEN 'bar' THEN ... ELSE ... END;

http://www.postgresql.org/docs/8.4/static/functions-conditional.html

Have a nice day,
--
Martijn van Oosterhout <kleptog(at)svana(dot)org> http://svana.org/kleptog/
> Patriotism is when love of your own people comes first; nationalism,
> when hate for people other than your own comes first.
> - Charles de Gaulle

In response to

Browse pgsql-general by date

  From Date Subject
Next Message kleptog 2011-06-19 11:02:12 Re: Referencing function value inside CASE..WHEN
Previous Message Craig Ringer 2011-06-19 09:33:12 Re: random backend crashes - how to debug ( Is crash dump handler released ? )