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

How to concat two string in postgresql function?

我想要一个 return 连接字符串的函数。在 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')); 

您应该在 PL/pgSQL 中使用 select into。并且为了避免名称冲突,不要将变量命名为与列相同:

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;

您的问题是赋值语句 :=.

行缺少分号

这使得以 RETURN (CONCAT 开头的行成为语句的续行,因此您会得到该行中报告的语法错误。