2016-09-15 50 views
1
CREATE OR REPLACE FUNCTION public.get_locations(
    location_word varchar(50) 
    ) 
RETURNS TABLE 
(
    country varchar(50), 
    city varchar(50) 
) 
AS $$ 
DECLARE 
location_word_ varchar(50); 
BEGIN 
location_word_:=concat(location_word, '%'); 
RETURN QUERY EXECUTE format(' (SELECT c.country, ''''::varchar(50) as city FROM webuser.country c 
            WHERE lower(c.country) LIKE %L LIMIT 1) 
           UNION 
           (SELECT c.country,ci.city FROM webuser.country c 
            JOIN webuser.city ci ON c.country_id=ci.country_id 
            WHERE lower(ci.city) LIKE %L LIMIT 4)', 
            location_word_, 
            location_word_) ; 

END 
$$ language PLPGSQL STABLE; 

SELECT public.get_locations('a'::varchar(50)); 

我明白了这一点;无法单独获取所有列值,而是获得一列中的所有值postgresql --9.5

+get_locations + 
+record   + 
------------------ 
+(Andorra,"") + 
+(Germany,Aach) + 
+(Germany,Aalen) + 
+(Germany,Achim) + 
+(Germany,Adenau)+ 

我该如何放置/获取值列如下列?否则,我无法正确匹配值。我应该列获取值列的国家和城市等

|country   | city  | 
------------------------------- 
| Andorra  | ""   | 
| Germany  | Aach  | 
| Germany  | Aalen  | 
| Germany  | Achim  | 
| Germany  | Adenau  | 
+3

呼叫在'FROM'条款的功能:'SELECT * FROM public.get_locations( 'A' :: VARCHAR(50))' – klin

+0

是正确的感谢.. – lowdegeneration

回答

1

你的函数声明为returns table所以你要使用它像一个表:

SELECT * 
FROM public.get_locations('a'::varchar(50)); 

无关,但:

你的函数太复杂了,你不需要动态SQL,也不需要PL/pgSQL函数。

可以简化到:

CREATE OR REPLACE FUNCTION public.get_locations(p_location_word varchar(50)) 
    RETURNS TABLE(country varchar(50), city varchar(50)) 
AS $$ 
(SELECT c.country, ''::varchar(50) as city 
FROM webuser.country c 
WHERE lower(c.country) LIKE concat(p_location_word, '%') 
LIMIT 1) 
UNION ALL 
(SELECT c.country ,ci.city 
FROM webuser.country c 
    JOIN webuser.city ci ON c.country_id = ci.country_id 
WHERE lower(ci.city) LIKE concat(p_location_word, '%') 
LIMIT 4) 
$$ 
language SQL;