简体   繁体   中英

How to convert two types of dates format into one date format in SQL?

I have three table in the database two of them contain dates however the dates are in two format, first 20-02-2011 and second is 25/09/2018. Let say each table have 10000 records and mixed with these two types of dates format. This why I why I create the column like --- (Transaction_Date, Varchar(10) Not Null)

I tried convert (Varchar(10),Transaction_Date,105) and also tried replace(convert(varchar(10),Transaction_Date,105),'/','-')

However date and year functions are still not working.

Please suggest a possible way.

How about this?

select replace(date, replace(Transaction_Date, '/', '-'), 105)

That is: (1) convert to a date and (2) replace the slash before converting.

You need to remember about your culture. Saved format vs server culture. But this is very possible

select Cast('2-22-2011' as datetime) f1,
       Cast('2/22/2011' as datetime) f2

I other words just use Cast

select cast(Transaction_Date as datetime) . .  .

But you should as soon as possible get rid of columns that saves date as string and create new date/time column, and insert your date values there

alter table tbl add column temp datetime
update tbl set temp = Cast(Transaction_Date  as datetime)
alter table tbl drop column Transaction_Date
alter table tbl add column Transaction_Date datetime 
update tbl set Transaction_Date = temp
alter table tbl drop column temp

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