'if' decision making in an SQL statement

Поиск
Список
Период
Сортировка
От nik@iii.co.uk
Тема 'if' decision making in an SQL statement
Дата
Msg-id 19980810112311.C3592@iii.co.uk
обсуждение исходный текст
Список pgsql-sql
Hi,

After searching the documentation and mailing list archives I can't find
anything about this -- I'm pretty certain it can't be done, but I
thought the mailing list might be able to help.

Is there anyway to perform IF...THEN...ELSE logic in a PostgreSQL query?

The specific problem I'm trying to solve is as follows. Given the class

    create table People (
    ID        int default nextvalue('seqPeople'),
    Firstname    text not null,
    Middlenames    text,
    Lastname    text not null
    );

    insert into People (Firstname, Middlenames, Lastname)
        values ('Nik', 'John', 'Clayton');

    insert into People (Firstname, Middlenames, Lastname)
        values ('Helen', 'Jane', 'Baker');

    insert into People (Firstname, Lastname)
        values ('Justin', 'Otto');

    ...

I want to create a query (which will be used as the basis for a view) that
merges the Firstname, Middlenames and Lastname columns together into one
column, with the correct spacing.

In Oracle, I'd use the decode() function for this, and write

    select ID, decode(Middlenames, null, Firstname || ' ' || Lastname,
                      Firstname || ' ' || Middlenames || ' ' || Lastname)
               as Fullname
      from People;

which expresses the logic

    IF Middlenames IS NULL THEN
        Firstname || ' ' || Lastname
    ELSE
        Firstname || ' ' || Middlenames || ' ' || Lastname
    END IF

and would give

   ID   Fullname
   -------------
   1    Nik John Clayton
   2    Helen Jane Baker
   3    Justin Otto
   ...

I can't see a way of doing this in PostgreSQL, and I don't really want
to have to do this sort of processing in the front end (since I have
several front ends, and putting the same logic in each one strikes me as
foolish when that logic really belongs in the database).

Many thanks for any suggestions.

N
--
"So it does!" said Pooh. "It goes in!"
"So it does!" said Piglet. "And it comes out!"
"Doesn't it?" said Eyeore. "It goes in and out like anything."

В списке pgsql-sql по дате отправления:

Предыдущее
От: "Stuart logan"
Дата:
Сообщение: Installing PostgreSQL 6.3.2 On Linux
Следующее
От: "James Oden"
Дата:
Сообщение: Re: [SQL] Installing PostgreSQL 6.3.2 On Linux