簡體   English   中英

如何在函數變量plpgsql中使用帶撇號的字符串

[英]How to use string with apostrophe in function variable plpgsql

您好,使用pgpsql函數查詢在postgresql的where子句中有撇號時,我遇到了麻煩,我知道手動可以執行以下操作:

select 'author''s'

但是我的話存儲在變量中,這是我的功能:

CREATE OR REPLACE FUNCTION public.fn_inserir_doc(caminho_arqv text, conteudo text)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
    declare
        conteudo_array text array;
        palavra text;
    begin
        execute 'insert into documento(caminho)
                    select ''' || caminho_arqv || '''
                    where not exists(select id 
                                    from documento
                                    where caminho='''||caminho_arqv||''')';
        conteudo_array := regexp_split_to_array(conteudo, E'\\s+');
        FOREACH palavra in array conteudo_array
        loop
              if length(palavra) >=3 then
                raise notice 'palavra: %', palavra;
                execute 'insert into termo(descricao)
                            select ''' || palavra || '''
                            where not exists(
                                            select id from termo
                                            where descricao='''||palavra||''')';
                execute 'insert into documento_termo(id_termo, id_documento, frequencia)
                            select t.id, d.id, 1
                            from termo t
                            cross join documento d
                            where t.descricao = '''|| palavra ||'''
                            and d.caminho = '''|| caminho_arqv ||'''
                            on conflict (id_termo, id_documento) do update set frequencia = documento_termo.frequencia + 1;';
                 end if;
        end loop;
    end;
$function$

以下示例是有問題的示例:

select id from termo
where descricao='''||palavra||'''

因為palavra包含單引號

使用美元引號和函數format() 例:

create or replace function test(str text)
returns setof text language plpgsql as $$
begin
-- instead of this:
--  return query execute 'select '''||str||'''::text';
-- use:
    return query execute format(
        $fmt$
            select %L::text
        $fmt$, str);
end $$;

select * from test('O''Brian');

  test   
---------
 O'Brian
(1 row) 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM