如何在 PostgreSQL (9.1) 函数中将字符转换为整数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14759987/
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
How do I convert a character to integer within a PostgreSQL (9.1) function?
提问by Georgy Passos
I have this following code:
我有以下代码:
BEGIN
x := split_part(text, ',', 1);
UPDATE albumphoto SET order = 1 WHERE idtable = 1 AND idx = x;
END
But my column table named idx
is a numeric type, and the split_part
returns a character type to the variable x
. I've tried using CAST
, but I don't know how to use it properly.
但是我命名的列表idx
是数字类型,并且split_part
将字符类型返回给变量x
。我试过使用CAST
,但我不知道如何正确使用它。
Any ideas?
有任何想法吗?
回答by Anton Kovalenko
Like this:
像这样:
UPDATE albumphoto SET order = 1 WHERE idtable = 1 AND idx = CAST (x AS INTEGER);
(Use appropriate numeric type instead of INTEGER
).
(使用适当的数字类型而不是INTEGER
)。
回答by Erwin Brandstetter
Or simpler:
或者更简单:
UPDATE albumphoto
SET order = 1
WHERE idtable = 1
AND idx = split_part(text, ',', 1)::int -- or whatever type it is
AND order IS DISTINCT FROM 1;
expression::type
is the simple (non-SQL-standard) Postgres way to cast. Details in the manual in the chapter Type Casts.
More about data types in PostgreSQL.
expression::type
是简单的(非 SQL 标准的)Postgres 转换方式。Type Casts一章的手册中的详细信息。
更多关于PostgreSQL 中的数据类型。
The last predicate I added is useful if order
could already be1
, in which case the update wouldn't change anything, but still cost the same. Rather do nothing instead. Related (consider the last paragraph):
如果我说的最后断言是有用的order
可能已经是1
,在这种情况下,更新不会改变什么,但费用仍然是相同的。而是什么都不做。相关(考虑最后一段):
And you don't needa variable here.
而且这里不需要变量。