如何在execute select语句where子句中使用变量而不会在列上出现错误?

时间:2019-07-12 14:07:14

标签: sql postgresql

我在运行存储过程时遇到麻烦,在该存储过程中,select语句在列名上抛出错误?

以下存储过程根据select语句的结果在循环内创建数据。问题在于哪里有WHERE r.report_status = IN_CONSIDERATION子句抛出异常,表明IN_CONSIDERATION不是列,是的,它确实不是列,也不应该是列,但是为什么它不起作用?有什么线索吗?非常感谢。我将在下面发布异常

 CREATE OR REPLACE FUNCTION public.field_validations2(
  )
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$
DECLARE
   cust_rec RECORD;
    new_signature_id bigint;
   inconsideration varchar;
BEGIN
    inconsideration := 'IN_CONSIDERATION';
    FOR cust_rec IN
        EXECUTE format('SELECT l.* FROM public.report_attached_person_many_to_many l INNER JOIN public.report r ON l.report_id = r.id WHERE r.report_status=%I', inconsideration)
    LOOP
  INSERT INTO public.report_signature(
    id, active, created, created_by, deleted, modified, modified_by, comment, status, type, staff, is_finished)
  VALUES (nextval('hibernate_sequence'),'true','1561713543512', '123', 'false', '1561713543512', '123', 'should be deleted after testing', '0', '1' , cust_rec.staff_id , 'false')
  RETURNING new_signature_id;
  INSERT INTO public.report_required_signatures_many_to_many(
      report_id, signature_id)
      VALUES (cust_rec.report_id, new_signature_id);
    END LOOP;
END
$BODY$;

ALTER FUNCTION public.field_validations2()
    OWNER TO postgres;

我得到的异常:

    ERROR:  column "IN_CONSIDERATION" does not exist
LINE 1: ...ort r ON l.report_id = r.id WHERE r.report_status="IN_CONSID...
                                                             ^
QUERY:  SELECT l.* FROM public.report_attached_person_many_to_many l INNER JOIN public.report r ON l.report_id = r.id WHERE r.report_status="IN_CONSIDERATION"
CONTEXT:  PL/pgSQL function field_validations2() line 8 at FOR over EXECUTE statement
SQL state: 42703

1 个答案:

答案 0 :(得分:0)

尝试在格式字符串中使用%L代替%I

EXECUTE format('SELECT l.* FROM public.report_attached_person_many_to_many l INNER JOIN public.report r ON l.report_id = r.id WHERE r.report_status=%L', inconsideration)

编辑

为什么要对您的选择查询使用execute?为什么不只是

FOR cust_rec IN (
  SELECT l.*
  FROM public.report_attached_person_many_to_many l
    INNER JOIN public.report r ON l.report_id = r.id
   WHERE r.report_status = inconsideration)
LOOP