gpt4 book ai didi

sql - 如何在执行 select 语句 where 子句中使用变量而不在列上出错?

转载 作者:行者123 更新时间:2023-11-29 13:40:00 25 4
gpt4 key购买 nike

我在运行存储过程时遇到了一些问题,其中 select 语句在列名称上抛出错误?

下面的存储过程根据 select 语句的结果在循环内创建数据。问题是 where 子句 WHERE r.report_status = IN_CONSIDERATION THROWING EXCEPTION INDICATING THAT IN_CONSIDERATION 不是一个列,是的,它确实不是一个列,它不应该是,但为什么它不起作用?任何线索?非常感谢。我将在下面发布异常(exception)情况

 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

最佳答案

尝试在格式字符串中使用 %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)

编辑

为什么要对选择查询使用执行?为什么不只是

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

关于sql - 如何在执行 select 语句 where 子句中使用变量而不在列上出错?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57008649/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com