2013-05-02 133 views
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 
+0

名單'time_of_call' – RichardTheKiwi 2013-05-02 20:19:11

回答

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 
+0

由於一些樣本數據,即偉大工程! – Kristen 2013-05-06 13:22:11