1 类型转换CAST / 双冒号(::) 概念
在PG 的SQL中,会经常看到::
的语法, "::"
符号其实是一个显示的类型转换符,作用等同于CAST。
官网的说明如下:
https://www.postgresql.org/docs/current/sql-createcast.html
By default, a cast can be invoked only by an explicit cast request, that is an explicit CAST(x AS typename) or x::typename construct.
也就是说,可以使用::
显示调用CAST,从而快速的一种数据类型的值转换为另一种数据类型。
2 使用示例
cndba=# select '2022'::int,'2022-DEC-17'::date;
int4 | date
------+------------
2022 | 2022-12-17
(1 row)
以上语法使用等于与如下的CAST:
cndba=# select CAST('2022' as int),CAST('2022-DEC-17' as date);
int4 | date
------+------------
2022 | 2022-12-17
(1 row)
当然使用类型转换时,如果表达式不能转换为目标类型,则会触发错误:
cndba=# select '2022year'::int;
ERROR: invalid input syntax for type integer: "2022year"
LINE 1: select '2022year'::int;
版权声明:本文为博主原创文章,未经博主允许不得转载。