【问题标题】:Variables not recognized in PostgreSQL function subquery?PostgreSQL 函数子查询中无法识别的变量?
【发布时间】:2010-01-12 14:19:58
【问题描述】:

工作解决方案:

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 文档,但我似乎无法找出原因。谁能弄清楚我的变量会发生什么?

【问题讨论】:

  • 我会将标题还原,以便人们能够在 Google 上找到它。这更多是关于位置参数而不是全文搜索:)

标签: sql postgresql stored-procedures


【解决方案1】:

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)来访问参数的属性。

【讨论】:

  • 啊,就是这样,谢谢。对于那些可能对用于搜索的存储过程感兴趣的人,我将用一个更有趣的标题来更新这个问题:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-25
相关资源
最近更新 更多