PostgreSQL:语法错误在或附近" ||"

时间:2014-07-01 05:19:26

标签: postgresql

我正在创建从中返回选择查询结果的函数。详细信息如下例所示:

示例

Create or replace function fun_test(cola text,colb text,rel text)
returns table(columna text,columnb text)as 
$Body$
Declare
table_name varchar :='Table_';
Begin
table_name := table_name || rel;

    return query select distinct || quote_ident(cola) ||,||quote_ident(colb)|| from || quote_ident(table_name) ;

end;
$Body$
language plpgsql;

错误

ERROR:  syntax error at or near "||"
LINE 10: ...| quote_ident(cola) ||,||quote_ident(colb)|| from || quote_i...
                                                              ^

1 个答案:

答案 0 :(得分:2)

您正在尝试动态构建查询,但您没有使用EXECUTE。那不行。你不能只用任意表达式代替标识符,例如:

return query select distinct || quote_ident(cola) ||,||quote_ident(colb)|| from || quote_ident(table_name) ;

这就是您收到错误的原因:

from ||
     ^

因为这在句法上是无效的废话。

相反,我认为你想要:

RETURN QUERY EXECUTE 'select distinct ' || quote_ident(cola) ||', '||quote_ident(colb)||' from '|| quote_ident(table_name);

哪个写得更好:

RETURN QUERY EXECUTE format('select distinct %I, %I from %I', cola, colb, table_name);