Обсуждение: Conver bool to text

Поиск
Список
Период
Сортировка

Conver bool to text

От
Edmund Bacon
Дата:
Is there a way to convert a boolean value to text and/or vice versa?

You can select 'true'::boolean,
which *seems* to convert a text string to boolean, but select 'true'::text::boolean
earns the message ERROR:  cannot cast type text to boolean

You can't go the other way eitherSELECT true::textERROR:  cannot cast type boolean to text

and to_char() doesn't know about booleans.

It's not that difficult to write a fuction to convert boolean to text, 
but I'm wondering if there's already something that does this?

-- 
Edmund Bacon <ebacon@onesystem.com>



Re: Conver bool to text

От
Marco Manfredini
Дата:

Edmund Bacon wrote:> Is there a way to convert a boolean value to text and/or vice versa?>[cause it doesn't work as
expected]>> It's not that difficult to write a fuction to convert boolean to text,> but I'm wondering if there's
alreadysomething that does this?You can help yourself by misusing the $type_in and $type_out functions: create or
replacefunction bool2text(bool) returns text as $$ select textin(boolout($1)); $$ language sql;  create cast (bool as
text)with function bool2text(bool); This is somewhat generic. Since the name of the *in and *out functioncan be read
frompg_type, the conversion function can even be generatedautomatic: /* warning: conversion via text representation
isn'talways right.*/ create or replace function make_conversion_function(s text, d text)returns void as $$ declare
tintext;   tout text;   xp text;  begin select typinput into tin from pg_catalog.pg_type where typname=d;  select
typoutputinto tout from pg_catalog.pg_type where typname=s;  xp:='create or replace function as_' || d || '(' || s ||
')returns '|| d || ' as $BODY$ select ' || tin || '(' || tout || '($1)) $BODY$language sql;';  execute xp;  /* create
castanalogue..*/ return;  end; $$ language plpgsql; select make_conversion_function('text','bool');select
make_conversion_function('bool','text');selectas_bool('true'),as_text(true); --- Marco