是否可以定义在CAST操作失败时返回的默认值?
例如,这样:
SELECT CAST('foo' AS INTEGER)
Run Code Online (Sandbox Code Playgroud)
将返回默认值而不是抛出错误?
mu *_*ort 27
CAST没有默认值:
类型转换指定从一种数据类型到另一种数据类型的转换.PostgreSQL接受两种等效的类型转换语法:
Run Code Online (Sandbox Code Playgroud)CAST ( expression AS type ) expression::type
除了要转换的表达式和所需的目标类型之外,语法中没有空间.
但是,您可以通过简单的功能手动完成:
create or replace function cast_to_int(text, integer) returns integer as $$
begin
return cast($1 as integer);
exception
when invalid_text_representation then
return $2;
end;
$$ language plpgsql immutable;
Run Code Online (Sandbox Code Playgroud)
然后,你可以说这样的话cast_to_int('pancakes', 0),并得到0.
PostgreSQL还允许您创建自己的强制转换,以便您可以执行以下操作:
create or replace function cast_to_int(text) returns integer as $$
begin
-- Note the double casting to avoid infinite recursion.
return cast($1::varchar as integer);
exception
when invalid_text_representation then
return 0;
end;
$$ language plpgsql immutable;
create cast (text as integer) with function cast_to_int(text);
Run Code Online (Sandbox Code Playgroud)
然后你可以说
select cast('pancakes'::text as integer)
Run Code Online (Sandbox Code Playgroud)
得到0或你可以说
select cast(some_text_column as integer) from t
Run Code Online (Sandbox Code Playgroud)
并获取无效整数0的some_text_column值.如果你想varchar使用这个自动默认的强制转换投射,那么你必须进行双重投射:
select cast(some_varchar::text as integer) from t
Run Code Online (Sandbox Code Playgroud)
仅仅因为你能做到这一点并不是一个好主意.我不认为将标准文本替换为整数转换是最好的想法.以上方法还需要你离开的标准varchar来integer单独投,你可以得到解决,如果你想自己做整体转换,而不是懒洋洋地撑船到内置的铸造.
NULL处理留给读者(简单)练习.
| 归档时间: |
|
| 查看次数: |
10569 次 |
| 最近记录: |