从plpgsql中的case语句返回值



如何从使用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(函数)CASE语句和PLpgSQL(过程)CASE语句的变化。

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

PLpgSQL (procedural) 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;

返回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;

最新更新