February 26, 2011

SQL Server: Convert to DateTime from other Datatypes




In this post, we will see how to convert data of different datatypes to a DateTime datatype, in SQL Server.

Sometimes date values that come from disparate sources may be of a different datatype other than DateTime such as int, varchar etc. In such cases we often need to convert the valuee back to DateTime. We will take two common scenarios of converting Int and Varchar datatype to DateTime

Consider the following examples:

Method 1 : Big Integer to Datetime

Assume that the date value along with time part is stored in Bigint datatype, use this query

bigint to datetime

Here’s the same query for you to try out:

declare @date bigint
set @date=20101219201119

select
cast(left(date,8)+' '+stuff(stuff(substring(date,9,6),5,0,':'),3,0,':') as datetime) from
(
select cast(@date as varchar(20)) as date
) as t

In the above example, the first 8 numbers denote a date and rest of numbers denote time values in the format HHMMSS. In the above code, left(date,8) extracts the date value. In order to have a proper date format we need to add ‘:’ in each of the time parts (hour, minute and second). The stuff function is used to add ‘:’ in the 3rd and 5th position and the entire string is converted to DateTime.

biginttodatetimeoutput

Method 2 : Varchar to Datetime

Assume that date value along with time part is stored in a Varchar datatype and a space seperates the date value from time values. Use this query:

varchar datetime

Here’s the same query for you to try out:

declare @date varchar(20)
set @date='20101219 201119'

select
cast(left(@date,8)+ ' ' +
stuff(stuff(substring(@date,10,6),5,0,':'),3,0,':') as datetime)

OUTPUT

varchar datetime output


Did you like this post?
kick it on DotNetKicks.com
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Madhivanan,an MSc computer Science graduate from Chennai-India, works as a works as a Lead Subject Matter Expert at a company that simplifies BIG data. He started his career as a developer working with Visual Basic 6.0, SQL Server 2000 and Crystal Report 8. As years went by, he started working more on writing queries in SQL Server. He now has good level of knowledge in SQLServer, Oracle, MySQL and PostgreSQL as well. He is also one of the leading posters at www.sqlteam.com and a moderator at www.sql-server-performance.com. His T-sql blog is at http://beyondrelational.com/blogs/madhivanan

 
  Feedback:

comments

0 Responses to "SQL Server: Convert to DateTime from other Datatypes"
 

Copyright © 2009-2014 All Rights Reserved for SQLServerCurry.com by Suprotim Agarwal | Terms and Conditions