简体   繁体   中英

Convert varchar dates (BC & AD) to date format in sql

Dates are stored like this in another table as varchars

select wkdocre from works;
   wkdocre   
-------------
 +1654/12/31
 +1706/12/31
 +1667/12/31
 -0332/12/31
 -0332/12/31
 -1295/12/31

And I want to insert these dates into another table with an attribute that is of type date like this

update ns_works set wor_workcreationdate=(select wkdocre from works where wor_workcreationdate=wkdocre);

I get this error

ERROR:  operator does not exist: ns_workcreationdate = dateofcreation
LINE 1: ...lect wkdocre from works where wor_workcreationdate=wkdocre);
                                                             ^
HINT:  No operator matches the given name and argument type(s). You might need to add explicit type casts.

Thank-you

Desired results

select wor_creationdate from ns_works;
   wor_creationdate   
-------------
 1654/12/31
 1706/12/31
 1667/12/31
 -0332/12/31
 -0332/12/31
 -1295/12/31

You need explicit conversion; try something like that:

... SET wor_workcreationdate =
        to_date(
           (select wkdocre
            from works
            where wor_workcreationdate = to_date(wkdocre, 'YYYY/MM/DD')),
           'YYYY/MM/DD'
        )

Writing years BC with a minus sign is incorrect though; PostgreSQL will interpret -1295 as 1296 BC , since year 0 is actually 1 BC. You might want to fix your works table and use YYYY/MM/DD BC as format specifier.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM