从plpgsql中的case语句返回值

时间:2015-10-18 16:05:33

标签: sql postgresql syntax-error case plpgsql

如何从使用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);

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:3)

所描述问题的原因是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;