Domanda

Ho creato un tipo enum dati personalizzati in questo modo:

create type "bnfunctionstype" as enum ( 
    'normal', 
    'library', 
    'import', 
    'thunk', 
    'adjustor_thunk' 
);

Da un'origine dati esterna ottengo interi nell'intervallo [0,4]. Mi piacerebbe convertire questi numeri interi ai loro valori enum corrispondenti.

Come posso fare questo?

sto usando PostgreSQL 8.4.

È stato utile?

Soluzione

SELECT (ENUM_RANGE(NULL::bnfunctionstype))[s]
FROM   generate_series(1, 5) s

Altri suggerimenti

Se si dispone di un enum in questo modo:

CREATE TYPE payment_status AS ENUM ('preview', 'pending', 'paid', 
                                    'reviewing', 'confirmed', 'cancelled');

È possibile creare un elenco di elementi validi in questo modo:

SELECT i, (enum_range(NULL::payment_status))[i] 
  FROM generate_series(1, array_length(enum_range(NULL::payment_status), 1)) i

Che dà:

 i | enum_range 
---+------------
 1 | preview
 2 | pending
 3 | paid
 4 | reviewing
 5 | confirmed
 6 | cancelled
(6 rows)
create function bnfunctionstype_from_number(int)
    returns bnfunctionstype
    immutable strict language sql as
$$
    select case ?
        when 0 then 'normal'
        when 1 then 'library'
        when 2 then 'import'
        when 3 then 'thunk'
        when 4 then 'adjustor_thunk'
        else null
    end
$$;
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top