Re: Declaring constants in SQL

From: Erwin Brandstetter <brsaweda(at)gmail(dot)com>
To: pgsql-general(at)postgresql(dot)org
Subject: Re: Declaring constants in SQL
Date: 2008-08-01 04:00:04
Message-ID: bdcff31f-59e8-4145-9b38-95db72ddeefa@p25g2000hsf.googlegroups.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On Jul 30, 10:53 pm, richard(dot)broer(dot)(dot)(dot)(at)gmail(dot)com ("Richard Broersma")
wrote:
> On Wed, Jul 30, 2008 at 1:16 PM, EXT-Rothermel, Peter M
> <Peter(dot)M(dot)Rother(dot)(dot)(dot)(at)boeing(dot)com> wrote:
> > Is there any means like (#define or DECLARE ) where I can write SQL like

(...)

> CREATE VIEW primary_colors_foos AS
>   SELECT * FROM foo
>    WHERE color = ANY( SELECT colorid
>                         FROM Colors
>                        WHERE colorname = ANY( 'red', 'blue', 'yellow' ));

Or even:
CREATE VIEW primary_color_foos AS
SELECT foo.* FROM foo JOIN color c USING (color_id)
WHERE c.colorname IN ('red', 'blue', 'yellow' );

If you have some constant values you need all over the place, you can
also resort to functions, which you can use much like CONSTANTs:

CREATE FUNCTION my_val()
RETURNS integer AS
$BODY$
BEGIN

RETURN 21;

END;
$BODY$
LANGUAGE 'plpgsql' IMMUTABLE;

Or, for the case at hand, an example in sql:
SELECT * FROM foo WHERE foo_id > myval();

CREATE FUNCTION my_colors()
RETURNS text[] AS
$$ SELECT ARRAY['red','green','blue'] $$
LANGUAGE 'sql' IMMUTABLE;

Use it like this:
SELECT * FROM foo WHERE color = ANY(myval());

Regards
Erwin

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Erwin Brandstetter 2008-08-01 04:06:00 Re: Declaring constants in SQL
Previous Message Henry - Zen Search SA 2008-08-01 02:20:35 Re: Clone a database to other machine