【问题标题】:Return value from case statement in plpgsqlplpgsql中case语句的返回值
【发布时间】:2015-10-18 16:05:32
【问题描述】:

如何从使用case 语句的用户定义函数中设置值(或直接返回值)?

create function is_bar(email varchar) returns boolean as
$$
declare returnValue boolean;
begin
  select case when exists
  (select * from (users join user_roles on users.userID = user_roles.userID)
  where user_email=email and user_role='bar')
    then (returnValue := TRUE);
    else (returnValue := FALSE);
  end;
  return returnValue;
end;
$$ language plpgsql;

给我:

ERROR:  syntax error at or near ":="
LINE 8: then (returnValue := TRUE);

【问题讨论】:

标签: sql postgresql syntax-error case plpgsql


【解决方案1】:

所描述问题的原因是 SQL(功能)CASE 语句和 PLpgSQL(过程)CASE 语句的更改。

SQL CASE(函数式):

BEGIN
   RETURN CASE WHEN EXISTS(..)
               THEN true /* value */
               ELSE false END; /* ended by END */
END;

PLpgSQL(过程)CASE

BEGIN
  CASE WHEN EXISTS(..)
    THEN
       RETURN true; /* statement */ 
    ELSE
       RETURN false;
  END CASE; /* ended by END CASE */
END;

还有一些其他的例子(结果相同):

a := CASE WHEN b < 10 THEN true ELSE false END;
a := b < 10;
CASE WHEN b < 10 THEN
  a := true;
ELSE
  a := false;
END CASE;

【讨论】:

    【解决方案2】:

    返回exists 运算符本身的结果会容易得多:

    CREATE FUNCTION is_bar(email VARCHAR) RETURNS BOOLEAN AS
    $$
    BEGIN
      RETURN EXISTS (SELECT *
                     FROM   users
                     JOIN   user_roles ON users.userID = user_roles.userID
                     WHERE  user_email = email AND user_role='bar')
    END;
    $$ LANGUAGE plpgsql;
    

    【讨论】:

    • 这样会容易得多。我将标记为已回答,但只是出于兴趣,为什么我当前的功能失败了?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多