POSTGRESQL 函数中的 CASE-WHEN

CASE-WHEN within function POSTGRESQL

我有一个函数可以将一些值插入 table,但在插入之前我想检查电子邮件地址是否正确。如果不是,则中断该函数并 returns 一个错误。情况属实,继续。

case when _email ~ '^[^@\s]+@[^@\s]+(\.[^@\s]+)+$' = true 
then raise exception 'Incorrect email'

_email 是函数的参数。 但它不起作用。我应该使用 "IF" 还是其他条件?

你应该可以使用plpgsql里面的case。显然你想做的事情也可以通过 if 语句来完成...

 case when _email ~ '^[^@\s]+@[^@\s]+(\.[^@\s]+)+$' = true then
           raise exception 'Incorrect email';
      else
           --proceed with insert
  end case;

CASE 有效,但 IF 似乎更合适。
您在表达式中有一些毫无意义的噪音,我认为您的逻辑倒退了:如果 _email 确实 匹配模式,则应触发 'Incorrect email':

IF _email ~ '^[^@\s]+@[^@\s]+(\.[^@\s]+)+$'  -- drop the pointless "= true"
THEN  -- do nothing - I inverted the logic
ELSE RAISE EXCEPTION 'Incorrect email';
END IF;

新的 ASSERT (Postgres 9.5+) 也可以工作,但这实际上是为了调试:

ASSERT _email ~ '^[^@\s]+@[^@\s]+(\.[^@\s]+)+$', 'Incorrect email';