Thursday, July 24, 2008

Convert string data into DataTime in Sql Server

In SQL Server, no direct funtion to convert interger string into time format. We need to do it by our own logic. See the below sample which convert integer string to datetime.



DECLARE

@DateTimeValue varchar(30),

@DateValue char(8),

@TimeValue char(6)



SELECT

@DateValue = '20080723',

@TimeValue = '211957'



SELECT @DateTimeValue =

convert(varchar, convert(datetime, @DateValue), 111)

+ ' ' + substring(@TimeValue, 1, 2)

+ ':' + substring(@TimeValue, 3, 2)

+ ':' + substring(@TimeValue, 5, 2)



SELECT

DateInput = @DateValue,

TimeInput = @TimeValue,

DateTimeOutput = @DateTimeValue

Use this tips!!!