[英]Converting an irregular varchar to datetime in sql server
I'm working on revamping a database right now, and all the datetime's are stored in varchar's formatted like so: DDMonYY hhmm (ex. 13Mar99 2032). 我现在正在修改数据库,所有日期时间都以varchar格式存储,如下所示:DDMonYY hhmm(例如13Mar99 2032)。
I don't have a lot of experience with SQL, as I only just finished my first year of college so I'm having a really hard time trying to get this to work so any help would be appreciated. 我在SQL方面没有太多经验,因为我刚完成大学一年级,所以我很难让它正常工作,所以任何帮助都将不胜感激。
All you should need to do for your particular string is to get a colon in between the hour and minute values. 您需要为特定的字符串做的所有事情就是在小时和分钟之间取一个冒号。 Something like: 就像是:
SELECT CAST(STUFF('13Mar99 2032', LEN('13Mar99 2032') - 1, 0, ':') AS datetime)
should work. 应该管用。
You can pick a datetime format and then shift parts of the string to match it. 您可以选择日期时间格式 ,然后将字符串的某些部分进行匹配。 For example, format 7 is: 例如,格式7为:
select convert(varchar(25), getdate(), 7)
-->
'Jun 23, 14'
So you can use substring
to transform your string: 因此,您可以使用substring
来转换您的字符串:
declare @orig varchar(30) = '13Mar99 2032'
declare @conv varchar(30)
select @conv = substring(@orig, 3, 3) + ' ' + substring(@orig, 1, 2) + ', ' +
substring(@orig, 6, 2) + ' ' + substring(@orig, 9, 2) + ':' + substring(@orig, 11, 2)
select @conv
, convert(datetime, @conv, 7)
-->
'Mar 13, 99 20:32' 1999-03-13 20:32:00.000
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.