如何在postgresql函数中连接两个字符串?

Rak*_*esh 0 postgresql concat plpgsql

我想要一个返回连接字符串的函数。在 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 
Run Code Online (Sandbox Code Playgroud)

我希望输出像'jh_shg_detail',但我收到这样的错误

ERROR:  syntax error at or near "("
LINE 9:    RETURN (CONCAT(state_short_name, '_shg_detail')); 
Run Code Online (Sandbox Code Playgroud)

a_h*_*ame 5

您应该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;
Run Code Online (Sandbox Code Playgroud)

但是对于像这样的简单 SQL 查询,您不需要 PL/pgSQL。您的子查询也不是真正必要的。您可以将其简化为where state_code = '34'

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;
Run Code Online (Sandbox Code Playgroud)