首页 > 解决方案 > 如何在 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')); 

标签: postgresqlplpgsqlconcat

解决方案


您应该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;

推荐阅读