【问题标题】:Append Single quotes in Query Postgres Function?在查询 Postgres 函数中附加单引号?
【发布时间】:2014-05-27 05:46:51
【问题描述】:

我试图在 postgres 函数的查询中附加单引号,但导致错误,请查看我的 postgres 函数,

CREATE OR REPLACE function test() returns my_type as $$
    declare rd varchar := '56';
    declare personphone varchar := 'Philip Dannes';
    declare result my_type;
    declare SQL VARCHAR(300):=null; 
        BEGIN        
        -- Mandatory / Static part of the Query here
        SQL = 'select pt.id from product_template pt inner join product_product pp on pt.id=pp.id where  ';

        IF rd IS NOT NULL        
            then        
                 SQL =  SQL || 'pp.radio_phone = '|| rd;
        else   
   SQL =  SQL || 'pp.radio_phone = '|| rd;
        end if;       

        IF personphone IS NOT NULL        
            then      
                SQL = SQL || ' and pp.person_phone = '|| personphone;   
            else
  SQL = SQL || ' and pp.person_phone = '|| personphone;    
        end if;

        SQL = SQL || ';';    

        EXECUTE SQL;         
return result;        
    END
$$ LANGUAGE plpgsql;

当我执行它时,它在“Philip Daves”上出现错误,并在附加为后返回查询,

Select pt.id from product_template pt inner join product_product pp on pt.id=pp.id where 
pp.radio_phone = 56 and  pp.person_phone = Philip Dave

我知道错误是因为 56 和 Philip Dave 不在单引号中,当我使用单引号执行函数返回查询时它工作正常。

如何在此查询中附加单引号??

我试过这样,

SQL = SQL || ' and pp.person_phone = '|| '' || personphone;

但 i 函数返回相同的查询

希望您的建议

提前致谢

【问题讨论】:

    标签: python sql postgresql postgresql-9.1 concat


    【解决方案1】:

    你需要大量重写它。

    首先,使用quote_identquote_literal 而不是手动引用。

    如果您使用的是较新的 PostgreSQL 版本,最好使用 format()%I%L 说明符作为标识符和文字。

    另外,尽量避免像这样迭代地构建字符串。尽可能使用带有CASEs 的表达式构建

    不需要任何varchar(300) 业务。只需使用text

    您的ELSE 子句似乎与您的IF ... THEN 包含相同的内容。我已经删除了它们。

    尝试使用RETURN QUERY EXECUTE,或者,如果您只获得一个值,则使用EXECUTE ... INTO

    DECLARE
        radiophone_clause text = '';
        personphone_clause text = '';
    BEGIN        
        IF rd IS NOT NULL then
            radiophone_clause = 'and pp.radio_phone = '|| quote_literal(rd);
        END IF;
    
        IF personphone IS NOT NULL then      
            personphone_clause = ' and pp.person_phone = '|| quote_literal(personphone);
        END IF;
    
        RETURN QUERY EXECUTE format('select pt.id from product_template pt inner join product_product pp on pt.id=pp.id where true %s %s', radiophone_clause, personphone_clause);
    END;
    

    the manual for info on quote_ident and quote_literal

    【讨论】:

    • 我能举出你提到的附加引号的例子吗?
    猜你喜欢
    • 1970-01-01
    • 2020-01-31
    • 1970-01-01
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    • 2020-05-09
    • 2012-10-14
    • 2017-06-04
    相关资源
    最近更新 更多