Table Name is tabelea
columns are name,expdate
. Both Column have not null contraints. Both column had character varying data type.
Values
name expdate
A '10-05-2015'
B ' '
Now i want to fetch the value which expdate
is not empty then convert to date format otherwise so empty. So i tried like this
select name,case when replace(expdate,' ','') <> '' then
to_char(cast(expdate as date),'dd-MM-yyyy') else null end from tablea
But is not work its show error invalid input syntax for type date: "' '" .
How to solve this?
i tried trim
also.
Postgresql 9.3
You can combine that in a single call if you convert empty strings to a null
value:
select name,
to_char(cast(nullif(trim(expdate), '') as date),'dd-MM-yyyy')
from tablea;
The cast
relies on some implicit data type conversion. It would be better to use to_date()
with an explicit format instead:
to_char(to_date(nullif(trim(expdate), ''), 'dd-mm-yyyy'),'dd-MM-yyyy')
SQLFiddle example: http://sqlfiddle.com/#!15/a9831/1
You can use the tilde to compare your string with the desired date pattern, before making it a date:
select
name,
case when expdate ~ '^[[:digit:]]{2}-[[:digit:]]{2}-[[:digit:]]{4}$' then
to_date(expdate, 'dd-MM-yyyy')
else
null
end as the_date
from tablea;
(Of course it is a bad idea to use a string data type to store dates in the first place.)
SQL fiddle: http://sqlfiddle.com/#!15/a66cf/2 .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.