格式化未收到日期时间的日期和时间

时间:2013-05-02 19:20:55

标签: sql-server

我从访问数据库收到日期和时间字段,它们是单独的varchar字段。我正在将数据导入sql数据库。我想将数据显示为日期时间字段,但我无法以正常方式格式化数据。我已经提出了一个子字符串来格式化数据,但是我遇到了将其放入游标或循环以获取所有数据以进行更新的问题。在将其移动到sql中的另一个表之前,我想首先格式化我的导入表。这是我有格式化日期和时间的代码。任何帮助将不胜感激。

时间

declare @result varchar(10), @time varchar(6), @hour varchar(2), @min varchar(2), @sec varchar (2);
Select @time = time_of_call from 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;

日期

declare @result varchar(12), @date varchar(8), @year varchar(4), @month varchar(2), @day varchar(2);
Select @date = date_of_call from 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

1 个答案:

答案 0 :(得分:0)

--- some sample data
create table import (time_of_call varchar(6), date_of_call varchar(8));
insert into import values ('101112', '20121110');
insert into import values ('134526', '20130201');

--- the query
select cast(date_of_call + ' ' +
            substring(time_of_call, 1, 2) + ':' +
            substring(time_of_call, 3, 2) + ':' +
            substring(time_of_call, 5, 2) as datetime) AsDateTime,
       cast(date_of_call + ' ' +
            substring(time_of_call, 1, 2) + ':' +
            substring(time_of_call, 3, 2) + ':' +
            substring(time_of_call, 5, 2) as datetime) AsString
from 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