sqlserver时间字符串的截取
昨天同学问了个sqlserver的问题,写了个简单的示例,如下:
问题:“15:00-16:30”拆分成“15:00-15:30”、“15:30-16:00”、“16:00-16:30”?
代码:
declare @time varchar(11)='15:00-19:30';
declare @bt datetime=CAST( SUBSTRING(@time,1,CHARINDEX('-',@time)-1) as datetime),
@et datetime=CAST(SUBSTRING(@time,CHARINDEX('-',@time)+1,LEN(@time)-CHARINDEX('-',@time)) as datetime);
declare @i int=DATEDIFF(MI,@bt,@et)/30,@j int=0;
create table #temp(timeName varchar(11))
while @j<@i
begin
insert into #temp values(CONVERT(varchar(5),DATEADD(MI,30*@j,@bt),114)+'-'+CONVERT(varchar(5),DATEADD(MI,30*(@j+1),@bt),114));
set @j=@j+1;
end;
select * from #temp;
drop table #temp;