在PostgreSQL中将整数转换为枚举

时间:2009-12-01 15:58:23

标签: sql postgresql enums integer type-conversion

我创建了一个自定义数据类型枚举,如下所示:

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

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

我该怎么做?

我正在使用PostgreSQL 8.4。

3 个答案:

答案 0 :(得分:11)

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

答案 1 :(得分: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)

答案 2 :(得分: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
$$;
相关问题