【发布时间】:2014-08-19 02:14:15
【问题描述】:
PostgreSQL 中是否有任何函数返回 Boolean,无论给定字符串是否为日期,就像 MSSQL 中的 ISDATE() 一样?
ISDATE("January 1, 2014")
【问题讨论】:
-
看起来不像是内置的。 But you can create your own
标签: sql postgresql date
PostgreSQL 中是否有任何函数返回 Boolean,无论给定字符串是否为日期,就像 MSSQL 中的 ISDATE() 一样?
ISDATE("January 1, 2014")
【问题讨论】:
标签: sql postgresql date
你可以创建一个函数:
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) 调用它作为返回布尔成功/失败值的测试。
@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;
【讨论】: