简体   繁体   中英

Convert varchar into date PostgreSQL

I need to convert dates of birth from type varchar into date. The table is called "customer" and the column is called "date_of_birth".

The Column has entries where the format of the date is dd.MM.YYYY and dd/MM/YYYY and I want to change every entry of the column.

The code I have right now is:

ALTER COLUMN date_of_birth type date USING to_date(date_of_birth, 'dd.MM.YYYY');

This code would work if the existing entries would all have the format "dd.MM.YYYY. Can someone help me adding the last piece of code, which also uses the other date format that I've mentioned above (dd/MM/YYYY).

I thank you for your time!

If you set datestyle appropriately, the type input function will do that automatically:

SET datestyle = ISO, DMY;

ALTER TABLE xxx
   ALTER date_of_birth TYPE date;

If you only need to deal with those two formats mentioned, you can use a CASE expression:

ALTER TABLE your_table
  ALTER COLUMN date_of_birth type date 
    USING case 
            when date_of_birth like '%/%' then to_date(date_of_birth, 'dd/MM/YYYY')
            else to_date(date_of_birth, 'dd.MM.YYYY')
          end;

If you have more then those two formats, you need to extend the tests to find out which format each value uses.

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