首页 > 解决方案 > 从函数中选择

问题描述

当满足第一个条件时,我需要退出该函数。但我收到错误“关系”选项卡“不存在”。可能是什么问题呢?例如

CREATE OR REPLACE function test_func(id int)
 RETURNS TABLE(results_q int4,flag character varying)
 LANGUAGE plpgsql
AS $function$
declare
    act_res int:= null;
    reason              varchar(255)        := null; 

begin
 with tab as (
     select 4/id  as res 
     where id = 2
    )

    select res into act_res from tab;

    if (act_res is not null)
    then
    return query 
    select res,
    case when res = 2 then 'Y'::varchar  end as flag
    from tab
    ;
    else 
  return query  with tab2 as (
     select 4+id  as res 
     )  
     select res,
     'N'::varchar as flag
    from tab2;

end if;
end;
$function$
;

如果我通过“2”,我想从选项卡中执行选择并完成该功能。感谢您的任何想法!

标签: sqlpostgresql

解决方案


问题在这里:

with tab as (
     select 4/id  as res 
     where id = 2
    )

您传递给函数的 id 不会在where子句中使用。

你可能想要这样的东西:

IF id = 2 THEN
   with tab as (
        select 4/id  as res 
    )

    select res into act_res from tab;
END IF;

一般提示,将参数命名为与 SQL 标识符相同的名称不是一个好主意,例如表、列名。plpgsql 在很多情况下都会抱怨。使用 _id 或 id_val 之类的东西。


推荐阅读