在 SELECT 查询中转换为自定义类型
Casting to custom type in SELECT query
我是 PostgreSQL 的新手,在这里完全迷路了。 (连标题都猜错了。。。)
我有例如这个:
postgres=# SELECT round(10000::decimal/100, 4);
round
----------
100.0000
(1 row)
是否有使用自定义类型获得相同结果的简单方法:
postgres=# SELECT 10000::my_type;
----------
100.0000
(1 row)
正式地,您可以使用 this simplified syntax:
创建任何类型
CREATE TYPE my_numeric (
INPUT = my_numeric_in,
OUTPUT = my_numeric_out,
<optional parameters>
)
其中 my_numeric_in
和 my_numeric_out
是支持函数。问题是
Generally these functions have to be coded in C or another low-level language.
这意味着它是一种扩展Postgres,你必须用函数的代码编译服务器或扩展,所以这绝对不是一个简单的方法。在实践中,这种输入转换可以使用触发器完成,但是所描述的转换看起来很奇怪,可能被认为是不好的做法。
您可能想将类型定义为 domain and create appropriate cast,但这行不通:
A cast to or from a domain type currently has no effect. Casting to or from a domain uses the casts associated with its underlying type.
实现类似效果的最简单方法是将值存储为 numeric
并使用转换函数,例如:
create or replace function my_numeric(numeric)
returns numeric language sql immutable as $$
select round(/100, 4)::numeric
$$;
select my_numeric(10000);
my_numeric
------------
100.0000
(1 row)
我认为这取决于类型。
例如,以下适用于 Postgres 9.3
# CREATE TYPE foo AS (num INT);
CREATE TYPE
# SELECT 300::foo;
ERROR: cannot cast type integer to foo
LINE 1: SELECT 300::foo
# SELECT (ROW(300)::foo).num;
num
-----
300
(1 row)
我是 PostgreSQL 的新手,在这里完全迷路了。 (连标题都猜错了。。。)
我有例如这个:
postgres=# SELECT round(10000::decimal/100, 4);
round
----------
100.0000
(1 row)
是否有使用自定义类型获得相同结果的简单方法:
postgres=# SELECT 10000::my_type;
----------
100.0000
(1 row)
正式地,您可以使用 this simplified syntax:
创建任何类型CREATE TYPE my_numeric (
INPUT = my_numeric_in,
OUTPUT = my_numeric_out,
<optional parameters>
)
其中 my_numeric_in
和 my_numeric_out
是支持函数。问题是
Generally these functions have to be coded in C or another low-level language.
这意味着它是一种扩展Postgres,你必须用函数的代码编译服务器或扩展,所以这绝对不是一个简单的方法。在实践中,这种输入转换可以使用触发器完成,但是所描述的转换看起来很奇怪,可能被认为是不好的做法。
您可能想将类型定义为 domain and create appropriate cast,但这行不通:
A cast to or from a domain type currently has no effect. Casting to or from a domain uses the casts associated with its underlying type.
实现类似效果的最简单方法是将值存储为 numeric
并使用转换函数,例如:
create or replace function my_numeric(numeric)
returns numeric language sql immutable as $$
select round(/100, 4)::numeric
$$;
select my_numeric(10000);
my_numeric
------------
100.0000
(1 row)
我认为这取决于类型。 例如,以下适用于 Postgres 9.3
# CREATE TYPE foo AS (num INT);
CREATE TYPE
# SELECT 300::foo;
ERROR: cannot cast type integer to foo
LINE 1: SELECT 300::foo
# SELECT (ROW(300)::foo).num;
num
-----
300
(1 row)