[英]SQL Server 2012 : Convert 12Hr AM/PM nchar to 24Hr DateTime Format
First post/question here. 这里的第一个帖子/问题。 I'm trying to convert an nchar to datetime.
我正在尝试将nchar转换为datetime。 The examples I looked for all displayed converting to 12 hour from 24 or just dealing with time and not the full date with conversion.
我查找的所有示例都显示从24转换为12小时,或者仅处理时间而不是转换的完整日期。 I'm not a native to SQL and I'm still learning the basics, so any help is appreciated.
我不是SQL的本机,并且我仍在学习基础知识,因此希望能提供任何帮助。
I have a table with this format that I've read from a bulk insert of .txt files. 我有一个表格是从大量的.txt文件中读取的。
Alarm is nchar of text, 警报是nchar文字,
AlarmTime is also nchar of the date I read from the text file. AlarmTime也是我从文本文件中读取日期的nchar 。
Alarm | AlarmTime
1 | 7/6/2016 10:10:42 AM
2 | 7/10/2016 6:41:23 PM
3 | 8/4/2016 4:35:53 PM
I would like to get this into a datetime format and not be store as nchar. 我想将其转换为日期时间格式,而不是将其存储为nchar。 Whenever I try to convert I get an error: Conversion failed when converting date and/or time from character string.
每当我尝试转换时,都会出现错误: 从字符串转换日期和/或时间时转换失败。
The result I'm looking for is this just stored as datetime: 我正在寻找的结果是这只是存储为datetime:
Alarm | AlarmTime
1 | 7/6/2016 10:10:42
2 | 7/10/2016 18:41:23
3 | 8/4/2016 16:35:53
I have considered separating the date and time in to separate columns using a delimiter and then putting them both back together later. 我曾考虑过使用分隔符将日期和时间分成多个单独的列,然后稍后将它们放回一起。 Or using the PM to add time then convert the colum to datetime.
或者使用PM添加时间,然后将列转换为日期时间。 But those both seemed cumbersome, and I figured there was something easy I was missing to accomplish this.
但是这些都显得很麻烦,而且我认为要实现这一目标我很容易错过。
Thanks in advance! 提前致谢!
Since you are on 2012, I would suggest that you use Try_Convert(). 由于您在2012年,因此建议您使用Try_Convert()。 This will trap any conversion errors.
这将捕获任何转换错误。 (Assuming your data string is m/d/y)
(假设您的数据字符串为m / d / y)
To identify the bogus records, try: 要识别伪造记录,请尝试:
Select * from YourTable where Try_Convert(datetime,AlarmTime) is null
Sample Code to Reformat your data 用于重新格式化数据的示例代码
Declare @YourTable table (Alarm int,AlarmTime nvarchar(50))
Insert Into @YourTable values
( 1,'7/6/2016 10:10:42 AM'),
( 2,'7/10/2016 6:41:23 PM'),
( 3,'8/4/2016 4:35:53 PM')
Select A.*
,ReFormated = format(try_convert(datetime,AlarmTime),'M/d/yyyy HH:mm:ss')
,AsDateTime = try_convert(datetime,AlarmTime)
From @YourTable A
Returns 返回
Alarm AlarmTime ReFormated AsDateTime
1 7/6/2016 10:10:42 AM 7/6/2016 10:10:42 2016-07-06 10:10:42.000
2 7/10/2016 6:41:23 PM 7/10/2016 18:41:23 2016-07-10 18:41:23.000
3 8/4/2016 4:35:53 PM 8/4/2016 16:35:53 2016-08-04 16:35:53.000
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.