2016-09-15 86 views
0
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; 

这是我得到的错误;使用Union子句postgresql时出错9.5

  • 错误:在语法错误或接近 “%”
  • LINE 2:WHERE较低(c.country)LIKE '百分比' LIMIT 1)

为什么我得到这个错误?

编辑

当我刚刚更换''::varchar(50)''''::varchar(50)它的工作!

+0

'%L'是应该是什么''%L'',在引号中的错字。也可能有其他问题,但这应该可以解决您报告的错误。 –

+0

为什么使用PL/pgSQL函数?为什么动态SQL?这可以通过简单的SQL函数并且不需要动态SQL来简化。 http://dpaste.com/1A96R5C –

+0

@a_horse_with_no_name我不知道,我通常使用这种方式...以及如果我不能解决这个问题,我会用你的代码... – lowdegeneration

回答

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; 
+2

占位符'%L' **将根据需要添加单引号。 Do ** not **将它们包含在格式字符串'''%L''中将在运行时生成额外的单引号。罪魁祸首就是''':: varchar(50)',应该是'''':: varchar(50)',就像你有的一样。 –

+0

然后尝试连接查询字符串和'location_word_',就像这样:'.. ILIKE'|| location_word_ || 'LIMIT ..'。 –

+0

或者你可以尝试在下面的字符串中使用双重'%':'location_word _:= concat(location_word,'%%');'。 [除了上面描述的格式说明符之外,还可以使用特殊序列%%输出字符%字符](https://www.postgresql.org/docs/9.5/static/functions-string.html#FUNCTIONS-字符串的格式)。 –