在Greenplum或者Deepgreen中,如果我们想直接把Boolean类型转化为Text,那么可能会让你失望,因为他们不支持这种直接转化,但是可以通过UDF的方式实现,下面来简单看一下这个过程。
首先,当我们运行下面的SQL来转换Boolean为Text类型时,会得到一个大写测错误:-D
DECLARE qgis_4 BINARY CURSOR FOR SELECT st_asbinary("location",'NDR'),ctid,"start_datetime"::text,"end_datetime"::text,"temperature"::text,"pressure"::text,boolout("rainfall")::text,"humidity"::text,"illuminance"::text,"uva"::text,"ubv"::text FROM "event"."weather_soratena" WHERE "location" && st_makeenvelope(136.92967584819169247,37.11712946054284856,137.3367917387353998,37.52424535108657011,4326) AND st_intersects(st_curvetoline("location"),st_makeenvelope(136.92967584819169247,37.11712946054284856,137.3367917387353998,37.52424535108657011,4326))
ERROR: cannot cast type cstring to text
LINE 1: ...ture"::text,"pressure"::text,boolout("rainfall")::text,"humi...
错误的原因是GP不支持将cstring转换成其他的数据类型(如下代码显示)
gpadmin=# select boolout('1')::text;
ERROR: cannot cast type cstring to text
LINE 1: select boolout('1')::text;
^
gpadmin=# select '1'::bool::text;
ERROR: cannot cast type boolean to text
LINE 1: select '1'::bool::text;
^
这时候我们该怎么办?放弃吗?当然不,我们可以通过UDF(User Defined Function)的方式来变通实现。这里我们定义一个BooleanToText函数,用来实现转换功能:
postgres=# CREATE FUNCTION BooleanToText(boolean) RETURNS text STRICT IMMUTABLE LANGUAGE PLPGSQL AS $$ BEGIN IF $1 IS TRUE THEN RETURN 'true'; ELSE RETURN 'false'; END IF; END; $$;
CREATE FUNCTION
postgres=# CREATE CAST (Boolean AS Text) WITH FUNCTION BooleanToText(boolean);
CREATE CAST
postgres=# select '1'::bool::text;
text
------
true
(1 row)
有朋友说,你开头的错误还是不能解决啊!姑且别急,接着看 ↓
针对cstring无法转换成text的问题,我们可以使用boolin函数先将cstring转换为boolean类型,然后在进行text的转换:
## 无法直接转换演示
postgres=# select boolout('1')::text;
ERROR: cannot cast type cstring to text
LINE 1: select boolout('1')::text;
## 可转换方式演示
postgres=# select boolin(boolout('1'::bool))::text;
boolin
--------
true
(1 row)
End~