0

我从访问数据库接收日期和时间字段,它们是单独的 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
4

1 回答 1

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
于 2013-05-02T20:22:43.507 回答