【问题标题】:Check whether string is a date Postgresql检查字符串是否为日期 Postgresql
【发布时间】:2014-08-19 02:14:15
【问题描述】:

PostgreSQL 中是否有任何函数返回 Boolean,无论给定字符串是否为日期,就像 MSSQL 中的 ISDATE() 一样?

ISDATE("January 1, 2014")

【问题讨论】:

标签: sql postgresql date


【解决方案1】:

你可以创建一个函数:

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;

然后,你可以这样使用它:

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)

【讨论】:

  • 请注意,每个begin ... exception 块都会创建一个子事务。因此,这可能会对性能产生重大影响。 PostgreSQL 确实需要一种通用的方式来调用数据类型转换,这种方式(a)返回 null 而不是失败时的异常;或 (b) 调用它作为返回布尔成功/失败值的测试。
  • 我在 2018 年仍然需要​​这个答案。谢谢。
  • 另请参阅stackoverflow.com/a/6730401/5248144 了解更通用的方法
  • 我在 2020 年仍然需要​​这个答案。“PostgreSQL 确实需要一种通用的方式来调用数据类型转换,这种方式要么 (a) 返回 null 而不是失败时的异常;要么 (b) 调用它作为一个返回布尔成功/失败值的测试。” -Craig R. 天哪,是的,请。
【解决方案2】:

@ntalbs 的答案很好,除了NULL 值的情况。如果我将NULL 值传递给true,我不希望is_date 返回true。这个调整解决了这个问题:

create or replace function is_date(s varchar) returns boolean as $$
begin
  if s is null then
     return false;
  end if;
  perform s::date;
  return true;
exception when others then
  return false;
end;
$$ language plpgsql;

【讨论】:

    猜你喜欢
    • 2020-06-23
    • 2011-11-18
    • 2018-06-15
    • 1970-01-01
    • 2012-06-17
    • 2011-10-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多