2010-01-12 68 views
1

工作的解決方案:PostgreSQL函數子查詢中不能識別的變量?

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文檔,我似乎無法找出原因。任何人都可以弄清楚我的變量會發生什麼?

+0

我回復標題後面,這樣的人就能夠找到它'Google'。這是更多關於位置參數比全文搜索:) – Quassnoi 2010-01-12 18:52:53

+0

好吧,這很有道理:) – mikl 2010-01-12 19:05:50

回答

3

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

Arguments to the SQL function are referenced in the function body using the syntax $n : $1 refers to the first argument, $2 to the second, and so on. If an argument is of a composite type, then the dot notation, e.g., $1.name , can be used to access attributes of the argument.

+0

啊,就是這樣,謝謝。我只需更新一個更有趣的標題給那些可能對搜索存儲過程感興趣的人:) – mikl 2010-01-12 18:41:43