在PostgreSQL中不使用函数的检查格式

问题描述 投票:0回答:1

如何检查日期值是否为预期格式,如果不是,我需要检查日期值为yyyy-mm-dd格式,然后显示状态0dob和doj的数据类型为varchar

我需要在不使用Postgresql中用户定义函数的情况下实现此逻辑

表格:Emp

Table: Emp

eid | ename | dob        | doj
1   | abc   | 1900-01-19 | 2019-02-20
2   | dx    | 1900-29-02 | 2019-04-22
3   | xy    | 1989-10-26 | 2018-27-02
4   |ji     | 2000-23-01 | 2019-29-04
5   |jj     |1980/04/09  |1999/08/20

基于以上数据,我希望检查日期格式为yyyy-mm-dd,如果没有,则标记将显示如下:

eid | dobdateformatstatus | dojdateformatstatus
1   | 1                   | 1
2   | 0                   | 1
3   | 1                   | 0
4   | 0                   | 0
5   |0                    |0

我对现有问题的解决方案是:

create function try_cast_to_date(p_in text)
returns date 
as $$
begin
    begin
        return $1::date;
    exception 
        when others then return null;
    end;
end;
$$
language plpgsql;
then use it in query:

select 
    eid, 
    ename, 
    (try_cast_to_date(dob) is not null) dobdateformatstatus, 
    (try_cast_to_date(doj) is not null) dojdateformatstatus  
from mytable

您能告诉我如何编写查询来实现此任务而不在PostgreSQL中使用用户定义的函数吗。

sql postgresql date validation postgresql-9.5
1个回答
0
投票

如果不是最正确的解决方案,那么用户定义的功能就是最清晰的解决方案。但是,如果没有用户定义的函数,则可以使用正则表达式来完成。以下内容提供了最通用的验证日期正则表达式,但是它确实错误地将29-Feb标记为leap年(验证正则表达式开始变得复杂),否则会验证日期。该正则表达式:

© www.soinside.com 2019 - 2024. All rights reserved.