sql server - Formatting date and time when they are not received as datetime -
i receiving date , time field access database , separate varchar fields. importing data sql database. want display data date time field can't data format in normal manner. have come substring format data having problems getting either cursor or loop of data update. want format import table first before move table in sql. here code have date , time format it. appreciated.
time
declare @result varchar(10), @time varchar(6), @hour varchar(2), @min varchar(2), @sec varchar (2); select @time = time_of_call import set @hour = substring(@time, 1, 2); set @min = substring(@time, 3, 2); set @sec = substring(@time, 5, 2); if @hour < '12' set @result = @hour + ':' + @min + ' am'; else if @hour >= '12' set @result = @hour + ':' + @min + ' pm'; select @result;
date
declare @result varchar(12), @date varchar(8), @year varchar(4), @month varchar(2), @day varchar(2); select @date = date_of_call import set @year = substring(@date, 1, 4); set @month = substring(@date, 5, 2); set @day = substring(@date, 7, 2); set @result = @month + '/' + @day + '/' + @year; select @result
--- sample data create table import (time_of_call varchar(6), date_of_call varchar(8)); insert import values ('101112', '20121110'); insert import values ('134526', '20130201'); --- query select cast(date_of_call + ' ' + substring(time_of_call, 1, 2) + ':' + substring(time_of_call, 3, 2) + ':' + substring(time_of_call, 5, 2) datetime) asdatetime, cast(date_of_call + ' ' + substring(time_of_call, 1, 2) + ':' + substring(time_of_call, 3, 2) + ':' + substring(time_of_call, 5, 2) datetime) asstring import; ----------------------- ----------------------- asdatetime asstring ----------------------- ----------------------- 2012-11-10 10:11:12.000 2012-11-10 10:11:12.000 2013-02-01 13:45:26.000 2013-02-01 13:45:26.000
Comments
Post a Comment