2016-09-15 79 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;