代码之家  ›  专栏  ›  技术社区  ›  mikl

PostgreSQL函数子查询中无法识别变量?

  •  1
  • mikl  · 技术社区  · 15 年前

    工作溶液:

    CREATE OR REPLACE FUNCTION my_search(tsq tsquery, translation_id integer, lang regconfig, count integer DEFAULT 10, skip integer DEFAULT 0)
    RETURNS TABLE(id int, chapter int, number int, headline text) AS $$
          SELECT id, chapter, number, ts_headline($3, text, $1, 'StartSel = <em>, StopSel = </em>'::text) FROM (
              SELECT id, chapter, number, text FROM lyrics
              WHERE $1 @@ search_text AND translation_id = $2
              LIMIT $4 OFFSET $5) AS matches;
    $$ LANGUAGE SQL STABLE;
    

    下面是原始问题。


    我一直试图创建一个postgresql存储过程,如下所示:

    CREATE OR REPLACE FUNCTION my_search(tsq tsquery, translation_id integer, lang text, count integer DEFAULT 10, skip integer DEFAULT 0)
    RETURNS TABLE(id int, chapter int, number int, headline text) AS $$
          SELECT id, chapter, number, ts_headline(lang, text, tsq, 'StartSel = <em>, StopSel = </em>') FROM (
              SELECT (id, chapter, number, text) FROM my_texts
              WHERE tsq @@ search_text AND translation_id = translation_id
              LIMIT count OFFSET skip) AS matches;
    $$ LANGUAGE SQL STABLE;
    

    但当我尝试将其加载到数据库中时,会出现以下错误:

    psql:scriptura.pgsql:7: ERROR:  column "tsq" does not exist
    LINE 5:           WHERE tsq @@ search_text AND translation_id = tran...
                            ^
    

    函数变量似乎不在子查询的作用域内。我一直在搜索postgresql文档,但似乎找不到原因。有人知道我的变量发生了什么吗?

    1 回复  |  直到 15 年前
        1
  •  3
  •   Quassnoi    15 年前

    LANGUAGE SQL 仅接受位置参数:

    CREATE OR REPLACE FUNCTION my_search(tsq tsquery, translation_id integer, lang text, count integer DEFAULT 10, skip integer DEFAULT 0)
    RETURNS TABLE(id int, chapter int, number int, headline text) AS $$
          SELECT id, chapter, number, ts_headline($3, text, $1, 'StartSel = <em>, StopSel = </em>') FROM (
              SELECT (id, chapter, number, text) FROM my_texts
              WHERE $1 @@ search_text AND translation_id = $2
              LIMIT $4 OFFSET $5) AS matches;
    $$ LANGUAGE SQL STABLE;
    

    documentation :

    SQL 函数体中使用以下语法引用函数 $n : $1 指的是第一个论点, $2 到第二个,等等。如果参数是复合类型,则使用点表示法,例如, $1.name ,可用于访问参数的属性。