2009-12-01 15 views
7

ho creato un tipo di dati enum personalizzato in questo modo:Conversione di un numero intero di Enum in PostgreSQL

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 in valori di enum corrispondenti.

Come posso fare questo?

Sto usando PostgreSQL 8.4.

risposta

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

Sembra estremamente elegante - ci proverò lunedì (quando torno in ufficio) e ti darò una risposta ... – BuschnicK

0
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 
$$; 
+0

Ho bisogno di farlo per diversi tipi di enumerazione, quindi mi piacerebbe davvero evitare di ripetere tutti i singoli valori e creare una stored procedure per ciascuno. – BuschnicK

2

Se si dispone di un enum come questo:

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

È possibile creare un elenco di elementi validi come questo:

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) 
Problemi correlati