Change Varchar field to Date MySQL

3

I need to fix a table that was built in the wrong way, the field that would be to store the date was created as varchar .

With this structure I can not select a certain period, since varchar are sorted from left to right in alphanumeric order. So if you select 05/30/2016 to 10/06/2016 it will bring an empty result.

The question is how to change the type of this field to date, because when I try to change the incorrect value error, because of the data already in the table.

How to do without losing the information that is contained in the table?

    
asked by anonymous 23.06.2016 / 17:52

2 answers

4

Do you need to convert data from dd / mm / yyyy to correct yyy / mm / dd?

If it is possible to solve using this script directly in the bank.

UPDATE tbl_data SET data =
    DATE_FORMAT(STR_TO_DATE(data, '%d/%m/%Y'), '%Y-%m-%d') 
WHERE data LIKE '__/__/____'

I created an event and ran the above code. See if it helps. After you run the code and update the dates change the field type directly into the database, from VARCHAR to DATE

    
23.06.2016 / 17:58
6

I think it's best to use the right kind, but the problem is not even being VARCHAR is the content having been written with the least relevant data before the most relevant. If I had been placed year, month and day, I would not have that problem. Databases are for storing raw data, not for storing cute texts to be displayed, this is the function of the application.

To do this you will have to take steps. First create a new temporary column of type DATE in the database. Then rotate a UPDATE to populate it with the dates. Then delete the old column and rename the new one with the old one (optionally).

UPDATE tabela SET datatmp = STR_TO_DATE(data_venda, '%d/%m/%Y')

Of course, if the application expects the old one to still exist, it will have to be dropped. But there's a problem, the new (or updated) data will only tinker with the old column. The right thing is to adapt all applications that access it to work with the new column.

    
23.06.2016 / 18:11