我有一个包含Start_Time
和End_Time
列的表格。数据存储为123000
的{{1}}和Start_Time
的{{1}}。
我希望查询将时间值返回为163000
和End_Time
。这有点容易实现吗?
提前致谢。
答案 0 :(得分:3)
Declare @YourTable table (Start_Time varchar(25), End_Time varchar(25))
Insert Into @YourTable values
('123000','163000'),
('090000','170000')
Select Start_Time = convert(varchar(8),convert(time,stuff(left(Start_Time,4),3,0,':')),100)
,End_Time = convert(varchar(8),convert(time,stuff(left(End_Time ,4),3,0,':')),100)
From @YourTable
返回
Start_Time End_Time
12:30PM 4:30PM
9:00AM 5:00PM
修改 - 在AM / PM之间添加空间
使用两个replace()可能会减少收益,格式()实际上可能更快
Declare @YourTable table (Start_Time varchar(25), End_Time varchar(25))
Insert Into @YourTable values
('123000','163000'),
('090000','170000')
Select Start_Time = replace(replace(convert(varchar(8),convert(time,stuff(left(Start_Time,4),3,0,':')),100),'AM',' AM'),'PM',' PM')
,End_Time = replace(replace(convert(varchar(8),convert(time,stuff(left(End_Time ,4),3,0,':')),100),'AM',' AM'),'PM',' PM')
From @YourTable
返回
Start_Time End_Time
12:30 PM 4:30 PM
9:00 AM 5:00 PM
答案 1 :(得分:1)
如果您需要much slower performing option,可以在SQL Server 2012 +中使用format()
:
create table t (Start_Time varchar(12), End_Time varchar(12))
insert into t values ('123000','163000'),('090000','170000')
select
Start_Time = format(convert(datetime,left(stuff(Start_Time,3,0,':'),5)),'h:mm tt')
, End_Time = format(convert(datetime,left(stuff(End_Time ,3,0,':'),5)),'h:mm tt')
from t
rextester演示:http://rextester.com/ZDSD64086
返回:
+------------+----------+
| Start_Time | End_Time |
+------------+----------+
| 12:30PM | 4:30 PM |
| 9:00AM | 5:00 PM |
+------------+----------+