Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
252 views
in Technique[技术] by (71.8m points)

sql server - How to convert varchar to datetime

I have a varchar column header (Prod_time) in the [YYYYmmdd hhmmss] format that I am trying to convert to datetime. I need to be able to pull data from a certain number of days, and I would like to be able to convert the varchar to datetime to facilitate this.

Is there a way to convert varchar to datetime? No special formatting of the datetime needed, only a data type conversion.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to force a couple characters in here so that the convert function knows how to deal with this. We can use STUFF for this pretty easily. This works given the provided string format.

declare @SomeChar varchar(20) = '20170216 100903'

select CONVERT(datetime, STUFF(STUFF(@SomeChar, 12, 0, ':'), 15, 0, ':'))

If at all possible you should consider converting the datatype to a datetime. It eliminates this kind of hassle and also prevents invalid values.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...