Reputation: 492
After my last post: SQL Query On Date When Type Is VARCHAR
I've decided I'm going to convert the column from a VARCHAR
to a DATE
type.
All the fields already have the data setout like "22/01/14".
Has anyone done this before.
Thanks,
Scott
Upvotes: 0
Views: 88
Reputation: 2449
I suggest you change table structure in several sql like this:
alter table `mytable` add `_IssueDate` DATE NOT NULL after `IssueDate`;
update `mytable` set `_IssueDate`=STR_TO_DATE(`IssueDate`, '%d/%m/%Y');
alter table `mytable` drop `IssueDate`;
alter table `mytable` change `_IssueDate` `IssueDate` DATE NOT NULL;
Upvotes: 0
Reputation: 37365
Use STR_TO_DATE()
like:
mysql> SELECT STR_TO_DATE('22/01/14','%d/%m/%Y'); +------------------------------------+ | STR_TO_DATE('22/01/14','%d/%m/%Y') | +------------------------------------+ | 2014-01-22 | +------------------------------------+ 1 row in set (0.00 sec)
-so apply it in your UPDATE
statement. If you're going to change column type, then it will not be safe to change that directly. Let's say your current column has name str_date
. Then:
ALTER TABLE t ADD new_date DATE
UPDATE t SET new_date=STR_TO_DATE(str_date,'%d/%m/%Y')
ALTER TABLE t DROP str_date
ALTER TABLE t CHANGE new_date str_date DATE
Upvotes: 1