[ACCEPTED]-Converting an Integer to Enum in PostgreSQL-type-conversion

Accepted answer
Score: 19
SELECT (ENUM_RANGE(NULL::bnfunctionstype))[s]
FROM   generate_series(1, 5) s

0

Score: 5

If you have an enum like this:

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

You can create 1 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)
Score: 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

More Related questions