【问题标题】:How to use string with apostrophe in function variable plpgsql如何在函数变量 plpgsql 中使用带撇号的字符串
【发布时间】:2017-06-28 23:37:05
【问题描述】:

您好,当我使用 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 包含单引号

【问题讨论】:

    标签: sql postgresql plpgsql


    【解决方案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) 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-15
      • 2011-05-12
      相关资源
      最近更新 更多