Microsoft SQL Server 有一个我认为非常明智的函数,如果转换不成功,try_cast()
它返回一个null
,而不是引发错误。
这使得可以使用CASE
表达式或 acoalesce
来回退。例如:
SELECT coalesce(try_cast(data as int),0);
Run Code Online (Sandbox Code Playgroud)
问题是,PostgreSQL 有没有类似的东西?
提出这个问题是为了填补我知识中的一些空白,但也有一个一般原则,即有些人更喜欢对某些用户错误做出不那么剧烈的反应。null
在 SQL 中返回 a比错误更容易。例如SELECT * FROM data WHERE try_cast(value) IS NOT NULL;
。根据我的经验,如果有 B 计划,有时可以更好地处理用户错误。
在将应用程序移植到 PostgreSQL (9.1) 时,我发现一个奇怪的 SQL 不兼容性与round()
函数有关,特别是采用指示舍入精度的第二个参数的版本。
在 MySQL 中, round(some_float_column, 2)
按预期工作,将some_float_column
四舍五入的值返回到小数点后两位。在 Postgres 中,它错误ERROR: function round(double precision, integer) does not exist
并建议HINT: No function matches the given name and argument types. You might need to add explicit type casts.
.
如文档所示...
http://www.postgresql.org/docs/9.1/static/functions-math.html
...Postgres 有两个轮函数,round(value)
它采用双精度或数字,并round(value, precision)
采用数字仅和一个整数。
所以,我不明白为什么 round 的两个参数形式不以 double 开头,但无论如何。在搜索中,我发现了这个问题的两种解决方案。一种是简单地创建我自己的版本round(value, precision)
,采用 (double, int) 并使用显式转换包装现有的 (numeric, int) 版本。这当然有效,但我不喜欢它(我的背景是 Oracle,它甚至没有真正的浮点类型)。在我看来,float/double 应该隐式转换为数字。事实证明,这些类型的 ASSIGNMENT 类型转换是预先定义的。但是 ASSIGNMENT 不适用于函数调用,正如我们在这里看到的,它需要是 IMPLICIT。与麻烦 …
我无法ON CONFLICT
处理外键为复合的外键列。这是一个例子。
create table foreign_table (
id_a text not null,
id_b text not null,
id integer primary key,
constraint ft_a_b_key unique (id_a, id_b)
);
create table my_table (
id integer,
ftable_id_a text,
ftable_id_b text,
constraint my_table_a_b_fk
foreign key (ftable_id_a, ftable_id_b) references foreign_table (id_a, id_b)
);
Run Code Online (Sandbox Code Playgroud)
使用此查询:
insert into tcell_test.my_table (id, ftable_id_a, ftable_id_b)
values (3, 'a3', 'b3') on conflict do nothing ;
Run Code Online (Sandbox Code Playgroud)
比如说,'a3'
不在 中foreign_table
,我希望ON CONFLICT
能够处理该错误。
相反,我收到错误:
Run Code Online (Sandbox Code Playgroud)[23503] ERROR: insert or update on table …
我的表包含列的索引total_balance
:
\d balances_snapshots
Table "public.balances_snapshots"
Column | Type | Collation | Nullable | Default
---------------+-----------------------------+-----------+----------+------------------------------------------------
user_id | integer | | |
asset_id | text | | |
timestamp | timestamp without time zone | | | now()
total_balance | numeric | | not null |
id | integer | | not null | nextval('balances_snapshots_id_seq'::regclass)
Indexes:
"balances_snapshots_pkey" PRIMARY KEY, btree (id)
"balances_snapshots_asset_id_idx" btree (asset_id)
"balances_snapshots_timestamp_idx" btree ("timestamp")
"balances_snapshots_user_id_idx" btree (user_id)
"balances_total_balance_idx" btree (total_balance)
Foreign-key constraints:
"balances_snapshots_asset_id_fkey" FOREIGN KEY (asset_id) …
Run Code Online (Sandbox Code Playgroud)