[英]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.我在数据库中有三个表,其中两个包含日期,但是日期有两种格式,第一个是 20-02-2011,第二个是 25/09/2018。 Let say each table have 10000 records and mixed with these two types of dates format.假设每个表有 10000 条记录并混合了这两种类型的日期格式。 This why I why I create the column like --- (Transaction_Date, Varchar(10) Not Null)
这就是为什么我创建这样的列的原因 --- (Transaction_Date, Varchar(10) Not Null)
I tried convert (Varchar(10),Transaction_Date,105)
and also tried replace(convert(varchar(10),Transaction_Date,105),'/','-')
我试过convert (Varchar(10),Transaction_Date,105)
也试过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.即:(1) 转换为日期和 (2)在转换之前替换斜线。
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
我换言之就是使用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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.