类型转换CAST(双冒号)

类型转换CAST / 双冒号(::)

在PG 的SQL中,会经常看到:: 的语法, "::" 符号其实是一个显示的类型转换符,作用等同于CAST。
可以使用::显示调用CAST,从而快速的一种数据类型的值转换为另一种数据类型。

使用示例
myba=# select '2022'::int,'2022-DEC-17'::date;
 int4 |    date
------+------------
 2022 | 2022-12-17
(1 row)

以上语法使用等于与如下的CAST:

myba=# select CAST('2022' as int),CAST('2022-DEC-17' as date);
 int4 |    date
------+------------
 2022 | 2022-12-17
(1 row)

当然使用类型转换时,如果表达式不能转换为目标类型,则会触发错误:

myba=# select '2022year'::int;
ERROR:  invalid input syntax for type integer: "2022year"
LINE 1: select '2022year'::int;

 

posted @ 2025-06-17 15:16  屠魔的少年  阅读(13)  评论(0)    收藏  举报