简体   繁体   English

将varchar的不同部分转换为日期时间,SQL

[英]Cast different parts of a varchar into a date time, SQL

I have a varchar that is an 8 digit number and I need to convert to a datetime. 我有一个8位数字的varchar,我需要转换为日期时间。 The production number is an automatically generated number from when the time the order was placed. 生产编号是从下订单时开始自动生成的编号。 For example, the production number 10090203 is actually the datetime 2015-10-09 02:03:00. 例如,生产编号10090203实际上是日期时间2015-10-09 02:03:00。 I need to cast a list of the varchar numbers into a datetime so that I can cross compare it to a list of date times. 我需要将varchar数字列表转换为日期时间,以便可以将其与日期时间列表进行交叉比较。 Here is how I convert datetime into varchar, but I am not sure how to go the other way around. 这是将datetime转换为varchar的方法,但是我不确定如何进行反方向转换。

 SELECT RIGHT('0' + CAST(DATEPART(M, table1.coldatetime) AS varchar), 2) 
+ RIGHT ('0' + Cast(DATEPART(DD, table1.coldatetime) AS varchar), 2) 
+ RIGHT('0' + CAST(DATEPART(HH, table1.coldatetime) AS varchar), 2)
+ RIGHT('0' + CAST(DATEPART(MINUTE, table1.coldatetime) AS varchar), 2)
AS 'CreatedNumber' FROM table1  

This should work for you: 这应该为您工作:

SELECT   
    DATEADD(mi,CAST(SUBSTRING(table1.coldatetime,7,2) AS INT),DATEADD(hour,CAST(SUBSTRING(table1.coldatetime,5,2) AS INT),CONVERT(datetime,'2015' + LEFT(table1.coldatetime,2)+SUBSTRING(table1.coldatetime,3,2))))
FROM
    table1
Select 
 STR_TO_DATE(CONCAT('2015',coldatetime,'00'),'%y','%m','%d','%H','%i','%s')
From Table1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM