PSQL 函数中存在多个 if

问题描述 投票:0回答:1

我有这样的代码,我在想是否有更好的方法来编写它?

create or replace FUNCTION "catalog"."checkUsers"(userID integer)
    RETURNS bool
    AS $$
DECLARE 
  v1 bool = false;
 
BEGIN
    if exists (
          SELECT somthing
          where condition1 )
     then
    v1 = true;
    end if;

    if exists (
          SELECT somthing
          where condition2 )
     then
    v1 = true;
    end if;

    if exists (
          SELECT somthing
          where condition3 )
     then
    v1 = true;
    end if;

    if exists (
          SELECT somthing
          where condition4 )
     then
    v1 = true;
    end if;

    RETURN v1;
END

我想重构它,因为我不确定代码是否以干净的方式编写。

sql postgresql function refactoring psql
1个回答
0
投票

在几乎没有提供任何信息的情况下,不可能提供明确的答案。 (选择条件字面上没有说明任何内容的内容)。然而生成模板是可以猜测的。通常,一系列 IF 条件在 SQL 中组合成一组 OR 条件。你会得到类似的东西:

create or replace function checkUsers(userId integer)
    returns boolean
   language sql
as $$
    select exists( select null 
                     from someTable 
                    where stId = userId 
                      and (   condition1 is not null
                           or condition2 is not null
                           or condition3 is not null
                           or condition4 is not null
                          )
                 );
 $$;

上面当然是对条件、条件的来源以及函数参数的使用做出了假设。 (参见演示

© www.soinside.com 2019 - 2024. All rights reserved.