2016-12-13 84 views
1

我收到的錯誤:集值函數,不能接受一組

set-valued function called in context that cannot accept a set

RETURN QUERY EXECUTE行執行此功能時

PLSQL $ cat lookup_email.pl 
CREATE OR REPLACE FUNCTION app.lookup_email(ident_id bigint,sess bigint,company_id bigint,email varchar) 
RETURNS SETOF RECORD as $$ 
DECLARE 
    rec RECORD; 
    comp_id bigint; 
    server_session bigint; 
    schema_name varchar; 
    query varchar; 
BEGIN 
    schema_name:='comp' || company_id; 
    select app.session.session into server_session from app.session where app.session.identity_id=ident_id and app.session.session=sess; 
    IF FOUND 
    THEN 
     BEGIN 
      query:='SELECT i.email,u.user_id FROM app.identity as i,' || schema_name || '.uzer as u WHERE i.email like ''%' || email || '%'' and i.identity_id=u.identity_id'; 
      RAISE NOTICE 'executing: %',query; 
      RETURN QUERY EXECUTE query; 
      RETURN; 
     EXCEPTION 
      WHEN OTHERS THEN 
       RAISE NOTICE ' query error (%)',SQLERRM; 

     END; 
    END IF; 
END; 
$$ LANGUAGE plpgsql; 

這是在psql的輸出中:

dev=> select app.lookup_email(4,730035455897450,6,'u'); 
NOTICE: executing: SELECT i.email,u.user_id FROM app.identity as i,comp6.uzer as u WHERE i.email like '%u%' and i.identity_id=u.identity_id 
NOTICE: query error (set-valued function called in context that cannot accept a set) 
lookup_email 
-------------- 
(0 rows) 

我知道查詢不包含任何錯誤,因爲它在另一個psql會話中工作:

dev=> SELECT i.email,u.user_id FROM app.identity as i,comp6.uzer as u WHERE i.email like '%u%' and i.identity_id=u.identity_id; 
    email  | user_id 
----------------+--------- 
[email protected] |  1 
(1 row) 

那麼,爲什麼Postgres的抱怨,如果我宣佈我的功能是作爲RETURNS SETOF RECORD?我的錯誤在哪裏?

+0

埃文解釋說的是真的很好,但你仍然不應該與目前的Postgres得到這個錯誤。你的版本是什麼? ('SELECT version()') –

回答

2

So, why is Postgres complaining if I declared my function being a SET of RECORD ??? Where is my error?

  1. 打電話給你設置在返回函數FROM子句。
  2. 總是指定你的類型。

它被稱爲集返回函數,但要指定複合型

這是完全有效的,

RETURNS SETOF RECORD $$ 

但是,您可能必須與調用它,

SELECT app.lookup_email(4,730035455897450,6,'u') 
AS t(col1 type, col2 type) 

你不能調用一個無類型的SRF的上下文是一個d oes沒有表格定義。這句法可以GETT可以得到討厭,所以才更容易改變RETURNS SETOF RECORD

RETURNS TABLE(col1 type, col2 type) AS $$ 

因爲每個表都有其下的同名文件類型,你也可以做

RETURNS SETOF myTable AS $$ 

查找the docs更多信息

+0

我喜歡使用'returns表(col_1類型,col_2類型)',而不是'cast'返回數據'select x,y from function_a()as(x type,y type)。 –