postgresql - 如何在 postgresql 函数中连接两个字符串?
问题描述
我想要一个返回连接字符串的函数。在 postgresql 中执行此函数后出现以下错误。
CREATE OR REPLACE FUNCTION getTableName ()
RETURNS text AS $$
DECLARE
state_short_name text;
BEGIN
state_short_name := (select lower(state_short_name) from mst_state where state_code in (SELECT substr(entity_code,1,2) FROM shg_detail_share WHERE entity_code = '3420006002001'))
RETURN (CONCAT(state_short_name, '_shg_detail'));
END;
$$ LANGUAGE plpgsql
我期望像'jh_shg_detail'这样的输出,但我收到这样的错误
ERROR: syntax error at or near "(" LINE 9: RETURN (CONCAT(state_short_name, '_shg_detail'));
解决方案
您应该select into
在 PL/pgSQL 中使用 a。并且为了避免名称冲突,不要将变量命名为与列相同:
CREATE OR REPLACE FUNCTION gettablename()
RETURNS text AS $$
DECLARE
l_state_short_name text;
BEGIN
select lower(state_short_name)
into l_state_short_name
from mst_state
where state_code in (SELECT substr(entity_code,1,2)
FROM shg_detail_share
WHERE entity_code = '3420006002001'));
RETURN CONCAT(state_short_name, '_shg_detail');
END;
$$ LANGUAGE plpgsql;
但是对于这样的简单 SQL 查询,您不需要 PL/pgSQL。您的子查询也不是必需的。您可以将其简化为where state_code = '34'
CREATE OR REPLACE FUNCTION gettablename()
RETURNS text
AS $$
select concat(lower(state_short_name), '_shg_detail')
from mst_state
where state_code = '34';
$$
LANGUAGE sql;
推荐阅读
- amazon-web-services - istio - 使用 vs 服务和 gw 代替负载均衡器不起作用
- azure-devops - 构建和部署具有相同版本的管道
- swagger - Slate 和 Swagger 会在什么场景下一起使用?
- php - 一条记录在 PHP 中的数据库中保存为两个或多个
- http-post - Indy HttpClient.Post 在为发布而构建但不在调试时给出范围检查错误 - 为什么?
- java - 如何在操作栏上隐藏和显示菜单项
- html - 如何为具有填充的图像添加边框?
- octave - 如何在 Octave 的模式中使用变量?
- python - 在 python 中使用装饰器时出现位置参数错误
- c# - C# 中的 AttributeProviderAttribute 工作和属性重定向机制