检查字符串是否是Postgresql的日期

use*_*541 10 sql postgresql date

postgresql中是否有一个函数返回boolean,无论给定的字符串是否像MSSQL一样是日期

PostgreSQL

谢谢!

nta*_*lbs 18

您可以创建一个功能:

create or replace function is_date(s varchar) returns boolean as $$
begin
  perform s::date;
  return true;
exception when others then
  return false;
end;
$$ language plpgsql;
Run Code Online (Sandbox Code Playgroud)

然后,您可以像这样使用它:

postgres=# select is_date('January 1, 2014');
 is_date
---------
 t
(1 row)

postgres=# select is_date('20140101');
 is_date
---------
 t
(1 row)

postgres=# select is_date('20140199');
 is_date
---------
 f
(1 row)
Run Code Online (Sandbox Code Playgroud)

  • 请注意,每个`begin ... exception`块都会创建一个子事务.因此,这可能会产生非平凡的性能影响.PostgreSQL确实需要一种通用的方式来调用一种数据类型,其方式是:(a)在失败时返回null而不是异常; 或(b)将其作为测试返回布尔成功/失败值. (5认同)
  • 我在2018年仍然需要​​这个答案.谢谢. (4认同)
  • 到 2020 年,我仍然需要这个答案。“PostgreSQL 确实需要一种通用方法来调用数据类型转换,其方式要么 (a) 返回 null 而不是失败时的异常;要么 (b) 将其作为返回布尔成功的测试调用/失败值。” -克雷格·R. 天啊,是的,拜托。 (2认同)