2017-06-26 75 views
0

您好我無法查詢,當我在有撇我在那裏用pgpsql功能子句中PostgreSQL的,我知道,手動我可以這樣做:如何在函數的變量PLPGSQL使用字符串撇號

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包含單引號

回答

1

使用dollar quoting和功能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) 
相關問題