在PostgreSQL中将整数转换为枚举

Bus*_*icK 8 sql postgresql enums integer type-conversion

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

create type "bnfunctionstype" as enum ( 
    'normal', 
    'library', 
    'import', 
    'thunk', 
    'adjustor_thunk' 
);
Run Code Online (Sandbox Code Playgroud)

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

我怎样才能做到这一点?

我正在使用PostgreSQL 8.4.

Qua*_*noi 13

SELECT (ENUM_RANGE(NULL::bnfunctionstype))[s]
FROM   generate_series(1, 5) s
Run Code Online (Sandbox Code Playgroud)


Joh*_*lin 5

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

CREATE TYPE payment_status AS ENUM ('preview', 'pending', 'paid', 
                                    'reviewing', 'confirmed', 'cancelled');
Run Code Online (Sandbox Code Playgroud)

您可以创建一个有效项目的列表,如下所示:

SELECT i, (enum_range(NULL::payment_status))[i] 
  FROM generate_series(1, array_length(enum_range(NULL::payment_status), 1)) i
Run Code Online (Sandbox Code Playgroud)

这使:

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