2012-05-23 198 views
0

我試圖創建一個函數,在其中一個表字段中搜索字符串,然後返回一個新的用戶表。基本上,一個表裏面我有Postgresql執行功能

create table fooSearchTable (
    id   integer, -- PG: serial 
    name  LongName unique not null, 
    queryDef LongString not null, 
    primary key (id) 
); 

其中queryDef是保存另一個查詢執行字符串。例如,一個行可能是

1 | resultName | select * from users where users.id = '4' 

我得到了這個函數格式

create or replace function searchUsers(_searchName text) returns table (userID integer) as $$ 
begin 
end; 
$$ language plpgsql stable; 

我需要運行一個SQL查詢來查找該行的_searchName比賽與是

啓動關閉功能
select queryDef from fooSearchTable f 
where f.name = _searchName; 

這將返回字符串,但我不知道如何在函數中執行此字符串,所以我可以得到一個userIDs表。任何幫助,將不勝感激。

+0

我猜想你讀過的[精說明書(http://www.postgresql.org/docs/current/static/plpgsql-statements.html# PLPGSQL-STATEMENTS-EXECUTING-DYN)說這個話題? –

+0

@ MilenA.Radev有點困惑如何從手冊中顯示的應用它 – SNpn

回答

1

像這樣的東西應該工作:

create or replace function searchUsers(_searchName text) 
    returns table (userID integer) 
as $$ 
    _query varchar; 
begin 
    select queryDef 
    into _query 
    from fooSearchTable f 
    where f.name = _searchName; 

    return query execute _query; 
end 
$$ language plpgsql; 

(未測試,因此它可能含有語法錯誤回報)

注意select .. into要求statment返回恰好一行,否則你會得到一個運行時錯誤。您需要確保條件達到此條件或在select語句上應用limit子句。

這是這裏解釋:
http://www.postgresql.org/docs/current/static/plpgsql-control-structures.html#AEN54092