English 中文(简体)
Converting an Integer to Enum in PostgreSQL
原标题:

I have created a custom data type enum like so:

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

From an external data source I get integers in the range [0,4]. I d like to convert these integers to their corresponding enum values.

How can I do this?

I m using PostgreSQL 8.4.

最佳回答
SELECT (ENUM_RANGE(NULL::bnfunctionstype))[s]
FROM   generate_series(1, 5) s
问题回答

If you have an enum like this:

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

You can create a list of valid items like this:

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

Which gives:

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




相关问题
Finding the Highest Value in an Enumeration

I m writing a method which determines the highest value in a .NET enumeration so I can create a BitArray with one bit for each enum value: pressedKeys = new BitArray(highestValueInEnum<Keys>());...

Conversion of Enum to Enumerable

To convert Enum to Enumerable ,I use public enum Flags { Trivial=1, Minor, Major, Critical } IEnumerable<int> n = Enumerable.Range((int)Flags.Trivial, (...

Subclass check, is operator or enum check

A couple of friends was discussing the use of inheritance and how to check if a subclass is of a specific type and we decided to post it here on Stack. The debate was about if you should implement a ...

Enum scoping issues

I try to keep things as local as possible, so I put enums at class scope, even if they are shared between two classes (I put it in the class that "goes better" with it.) This has worked out great, but ...

How do I sort enum members alphabetically in Java?

I have an enum class like the following: public enum Letter { OMEGA_LETTER("Omega"), GAMMA_LETTER("Gamma"), BETA_LETTER("Beta"), ALPHA_LETTER("Alpha"), private final String ...

C++ enum value initialization

I have an enum declared in my code as: enum REMOTE_CONN { REMOTE_CONN_DEFAULT = 0, REMOTE_CONN_EX_MAN = 10000, REMOTE_CONN_SD_ANNOUNCE, REMOTE_CONN_SD_IO, REMOTE_CONN_AL, ...

WCF: Enforce equal DataContracts on both sides

I m wondering if it is possible to have WCF make sure that the DataContracts on both sides of a connection are exactly the same (and throw an exception when trying to connect if they are not). For ...

热门标签