Recognizing invalid dates in postgresql

那年仲夏 提交于 2021-01-27 20:33:09

问题


I am trying to parse dirty input into postgres tables. I have a problem with a 'date' field occasionally containing non-dates such as '00000000' or '20100100'. pg refuses to accept these, and rightly so.

Is there a way to have postgres recognize invalid dates (or only valid dates, if that works better), so I can substitute a sensible default?

(I've considered building a table listing the dates I'm willing to accept, and use that in a sub-select, but that seems awfully inelegant.)

Cheers,

Jurgen


回答1:


http://www.tek-tips.com/viewthread.cfm?qid=1280050&page=9

A more generic approach than the above:

create function safe_cast(text,anyelement) 
returns anyelement 
language plpgsql as $$ 
begin 
    $0 := $1; 
    return $0; 
    exception when others then 
        return $2; 
end; $$;

Used like this:

select safe_cast('Jan 10, 2009', '2011-01-01'::timestamp)
select safe_cast('Jan 10, 2009', null::timestamp)

Credited to the friendly dudes at the #postgresql irc channel. :)




回答2:


You could write a pgsql function with an exception handling block.



来源:https://stackoverflow.com/questions/6730095/recognizing-invalid-dates-in-postgresql

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!