Попробуйте это
-- Create table
CREATE TABLE [dbo].[TableA](
[ID] [int] NULL,
[StartTime] [datetime] NULL,
[EndTime] [datetime] NULL
) ON [PRIMARY]
GO
--insert sample data
Insert Into TableA (ID,StartTime,EndTime) values(1 ,'2012-03-22 06:00:00.000', '2012-03-22 06:30:00.000' )
Insert Into TableA (ID,StartTime,EndTime) values(2 ,'2012-03-22 06:15:00.000', '2012-03-22 06:45:00.000' )
Insert Into TableA (ID,StartTime,EndTime) values(3 ,'2012-03-22 06:30:00.000', '2012-03-22 07:00:00.000' )
Insert Into TableA (ID,StartTime,EndTime) values(4 ,'2012-03-22 06:45:00.000', '2012-03-22 07:15:00.000' )
Insert Into TableA (ID,StartTime,EndTime) values(5 ,'2012-03-22 07:00:00.000', '2012-03-22 07:30:00.000' )
Insert Into TableA (ID,StartTime,EndTime) values(6 ,'2012-03-22 07:15:00.000', '2012-03-22 07:45:00.000' )
Insert Into TableA (ID,StartTime,EndTime) values(8 ,'2012-03-22 07:30:00.000', '2012-03-22 08:00:00.000' )
Insert Into TableA (ID,StartTime,EndTime) values(9 ,'2012-03-22 07:45:00.000', '2012-03-22 08:15:00.000' )
Insert Into TableA (ID,StartTime,EndTime) values(10 ,'2012-03-22 08:00:00.000', '2012-03-22 08:30:00.000' )
Insert Into TableA (ID,StartTime,EndTime) values(11 ,'2012-03-22 08:15:00.000', '2012-03-22 08:45:00.000' )
Insert Into TableA (ID,StartTime,EndTime) values(12 ,'2012-03-22 08:30:00.000', '2012-03-22 09:00:00.000' )
Insert Into TableA (ID,StartTime,EndTime) values(13 ,'2012-03-22 08:45:00.000', '2012-03-22 09:15:00.000' )
Insert Into TableA (ID,StartTime,EndTime) values(14 ,'2012-03-22 09:00:00.000', '2012-03-22 09:30:00.000' )
Insert Into TableA (ID,StartTime,EndTime) values(15 ,'2012-03-22 09:15:00.000', '2012-03-22 09:45:00.000' )
Insert Into TableA (ID,StartTime,EndTime) values(16 ,'2012-03-22 09:30:00.000', '2012-03-22 10:00:00.000' )
--query
Declare @AnchorElement int
Set @AnchorElement = (Select top 1 ID from TableA
where '2012-03-22 06:00:00.000'
between StartTime and EndTime
Order by StartTime
)
;
With ListStartingAtDate (ID, StartTime, EndTime ,Level ) as
(
-- Anchor Timeframe definition
select ID, StartTime, EndTime , 0 as Level From TableA
--Where ID = @AnchorElement
-- StartTime has to be matched exactly
WHERE StartTime = '2012-03-22 06:00:00.000'
UNION ALL
-- Recursive Timeframe definition
select a.ID, a.StartTime, a.EndTime , Level +1
From TableA a
INNER JOIN ListStartingAtDate b
ON a.StartTime = b.EndTime
)
select * from ListStartingAtDate
where StartTime >= '2012-03-22 06:00:00.000' and EndTime <= '2012-03-22 08:00:00.000'