sql - 从函数中选择
问题描述
当满足第一个条件时,我需要退出该函数。但我收到错误“关系”选项卡“不存在”。可能是什么问题呢?例如
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”,我想从选项卡中执行选择并完成该功能。感谢您的任何想法!
解决方案
问题在这里:
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 之类的东西。
推荐阅读
- sql - 我们如何删除由 LEAD 函数创建的列
- redirect - IIS 重定向到 https 共享点
- python - 修复重命名文件夹时文件夹内文件的混合
- gemfire - Gemfire 作为消息源
- kotlin - 如何使用 Koin 测试 Ktor 模块?
- sql - 为每个 BST 节点构建遍历路径
- java - 如何使用 selenium java 处理网页上的两个垂直滚动
- javascript - 获取响应后执行代码 - Javascript
- python - f.write(response.content, f) TypeError: TextIOWrapper.write() 只接受一个参数(给定 2 个)
- r - 调查数据的收敛问题