Postgresql函数中的Concat文本变量

时间:2018-09-19 19:30:51

标签: postgresql plpgsql

我有这段代码,我想连接变量,但是不起作用。 这是我对视图的DDL代码:

CREATE OR REPLACE function acd.add_credito2()
RETURNS void
SET SCHEMA 'acd'
SET search_path = acd
AS $$
DECLARE
    auxsigla text;
    auxnome text;
    _sql text := 'CREATE OR REPLACE VIEW acd.teste AS SELECT md.matriz_disciplina_id AS id, dcp.nome, mc.curso, mc.versao AS matriz';    
    _join text := ' FROM matriz_disciplina as md LEFT JOIN disciplina as dcp ON md.disciplina_id = dcp.disciplina_id LEFT JOIN matriz_curricular as mc ON md.matriz_curricular_id = mc.matriz_curricular_id';

BEGIN
    select into auxsigla, auxnome from ( select sigla, nome from acd.categoria_credito where categoria_credito_id = 9) as foo;
    _join := _join || ' LEFT JOIN (SELECT creditos, matriz_disciplina_id FROM acd.disciplina_credito WHERE categoria_credito_id = ' || x || ') AS ' || "auxsigla" ' ON ' || "auxsigla" || '.matriz_disciplina_id = md.matriz_disciplina_id';
        _sql := _sql || ', ' || "auxsigla" || '.' || auxnome || ' AS ' || auxnome;

    _sql := _sql || _join;

    EXECUTE _sql;
END;
$$ LANGUAGE plpgsql

所以,当我执行功能时

database-1=# select acd.add_credito2();

出现此错误:

ERROR:  type "auxsigla" does not exist
LINE 1: ...WHERE categoria_credito_id = ' || x || ') AS ' || "auxsigla"...
                                                             ^
QUERY:  SELECT _join || ' LEFT JOIN (SELECT creditos, matriz_disciplina_id FROM acd.disciplina_credito WHERE categoria_credito_id = ' || x || ') AS ' || "auxsigla" ' ON ' || "auxsigla" || '.matriz_disciplina_id = md.matriz_disciplina_id'
CONTEXT:  PL/pgSQL function add_credito2() line 13 at assignment

有人可以帮助我吗?我不知道现在该怎么办。

(我知道,此研究视图没有目的,但这是我想在实际视图中使用的想法)

1 个答案:

答案 0 :(得分:0)

错误来自此构造:

"auxsigla" ' ON '

您忘记了这两个标记之间的串联运算符||,现在SQL解析器将其解释为

data_type string_constant

这是一种指定某种数据类型的常量的方法。

可行的示例为DATE '2018-09-20'INTEGER '-20'

您的函数还有很多其他问题,我可以发现其中两个:

  • select into auxsigla, auxnome from将始终将变量设置为NULL,因为您忘记了指定要选择的列。

  • 在编写动态查询字符串时,您没有正确转义单引号。如果auxsigla的值为with'quote怎么办?

    为此使用format()quote_literal()quote_ident()