Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
668 views
in Technique[技术] by (71.8m points)

mysql - How to convert a varchar column type to date type without losing the dates

I am looking for a way to change the datatype of a column. Currently, in my database, the date columns types were defined as varchar and I need to convert them back to the date type.

Any idea how to do it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You will need to adapt this based your your exact table structure but something like;

CREATE TABLE temp (startdate varchar(255), stuff varchar(255));

INSERT INTO temp
SELECT startdate,stuff
FROM mytable;

TRUNCATE TABLE mytable;

ALTER TABLE mytable ALTER COLUMN startdate DATETIME NOT NULL;

INSERT INTO mytable
SELECT CAST(startdate AS DATETIME), stuff FROM temp;

DROP TABLE temp;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...