PostgreSQL。CREATE CAST '字符变化'到'整数'

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4760759/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-10 22:47:32  来源:igfitidea点击:

Postgresql. CREATE CAST 'character varying' to 'integer'

postgresql

提问by Simon

I want to CREATE CAST a suitable function to convert 'character varying' to 'integer'. Can anyone suggest a function? Everything I try fails.

我想 CREATE CAST 一个合适的函数来将“字符变化”转换为“整数”。任何人都可以建议一个功能吗?我尝试的一切都失败了。

回答by Peter Eisentraut

Use this:

用这个:

CREATE CAST (varchar AS integer) WITH INOUT [AS IMPLICIT];

It uses the input/output functions of the data types involved.

它使用所涉及数据类型的输入/输出函数。

回答by Michael Blood

The function above works if you update your SQL to do an explicit cast. However, if you add 'as implicit' to the end of your "create cast" statement, Postgres will be able to automatically figure out what you are trying to do when you compare an integer with a varchar that can be converted to an integer.

如果您更新 SQL 以执行显式转换,则上述函数有效。但是,如果您在“create cast”语句的末尾添加“作为隐式”,当您将整数与可以转换为整数的 varchar 进行比较时,Postgres 将能够自动确定您要执行的操作。

Here is my updated statement that seemed to work "implicitly":

这是我更新的声明,似乎“隐式”起作用:

CREATE FUNCTION toint(varchar) 
  RETURNS integer 
  STRICT IMMUTABLE LANGUAGE SQL AS 
'SELECT cast( as integer);';

CREATE CAST (varchar AS integer) WITH FUNCTION toint(varchar) as Implicit;

回答by Oscar Raig Colon

I got the same error. I have a COLUMN

我得到了同样的错误。我有一个列

code

代码

declared as type character varying(20) and a local variable

声明为类型字符变化(20)和局部变量

l_code

l_code

declared as type int.

声明为 int 类型。

I solved replacing in the procedure

我在程序中解决了更换

SELECT 
...
WHERE
code = l_code AND
..

with

code = cast( l_code as character varying)   AND

回答by a_horse_with_no_name

I assume you want to get back the behaviour of Postgres 8.3 regarding implicit casting.

我假设您想恢复 Postgres 8.3 关于隐式转换的行为。

See this blog entry for examples:
http://petereisentraut.blogspot.com/2008/03/readding-implicit-casts-in-postgresql.html

有关示例,请参阅此博客条目:http:
//petereisentraut.blogspot.com/2008/03/readding-implicit-casts-in-postgresql.html

Oh: and bug that vendor of the software to fix the broken SQL ;)

哦:还有那个软件供应商的 bug 来修复损坏的 SQL ;)

Edit

编辑

This should do it:

这应该这样做:

CREATE FUNCTION toint(varchar) 
  RETURNS integer 
  STRICT IMMUTABLE LANGUAGE SQL AS 
'SELECT cast( as integer);';

CREATE CAST (varchar AS integer) WITH FUNCTION toint(varchar);