2009-12-01 20 views
7

转换的整数枚举我已创建自定义数据类型枚举像这样:PostgreSQL中

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

从外部数据源我得到整数的范围是[0,4]。我想将这些整数转换为相应的枚举值。

我该怎么做?

我正在使用PostgreSQL 8.4。

回答

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

这看起来非常优雅 - 我会在星期一尝试它(当我回到办公室时)并相信您的答案... – 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

我需要为几个枚举类型执行此操作,所以我真的很想避免重复所有单个值并为每个值创建一个存储过程。 – BuschnicK

2

如果你有一个这样的枚举:

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

您可以创建这样有效的项目清单:

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

其中给出:

i | enum_range 
---+------------ 
1 | preview 
2 | pending 
3 | paid 
4 | reviewing 
5 | confirmed 
6 | cancelled 
(6 rows)