使用Union子句postgresql 9.5

时间:2016-09-15 07:49:51

标签: postgresql postgresql-9.5

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;

这是我得到的错误;

  • 错误:语法错误在或接近"%"
  • 第2行:在哪里更低(c.country)LIKE' a%'限制1)

为什么我会收到此错误?

修改

当我刚用''::varchar(50)取代''''::varchar(50)时,它就有效了!

1 个答案:

答案 0 :(得分: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 c.country ILIKE ''%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 ci.city ILIKE ''%L'' LIMIT 4)', 
                                    location_word_,
                                    location_word_ )    ;

END
$$ language PLPGSQL STABLE;