为了从选择的结果集开始/结束时间中提取小时数,然后创建一个每小时迭代的新表,我必须做类似的事情。
DECLARE @tCalendar TABLE
(
RequestedFor VARCHAR(50),
MeetingType VARCHAR(50),
RoomName VARCHAR(MAX),
StartTime DATETIME,
EndTime DATETIME
)
INSERT INTO @tCalendar(RequestedFor,MeetingType,RoomName,StartTime,EndTime)
SELECT req as requestedfor
,meet as meetingtype
,room as rooms
,start as starttime
,end as endtime
--,u.datetime2 as endtime
FROM mytable
DECLARE @tCalendarHours TABLE
(
RequestedFor VARCHAR(50),
MeetingType VARCHAR(50),
RoomName VARCHAR(50),
Hour INT
)
DECLARE @StartHour INT,@EndHour INT, @StartTime DATETIME, @EndTime DATETIME
WHILE ((SELECT COUNT(*) FROM @tCalendar) > 0)
BEGIN
SET @StartTime = (SELECT TOP 1 StartTime FROM @tCalendar)
SET @EndTime = (SELECT TOP 1 EndTime FROM @tCalendar)
SET @StartHour = (SELECT TOP 1 DATEPART(HOUR,DATEADD(HOUR,0,StartTime)) FROM @tCalendar)
SET @EndHour = (SELECT TOP 1 DATEPART(HOUR,DATEADD(HOUR,0,EndTime)) FROM @tCalendar)
WHILE @StartHour <= @EndHour
BEGIN
INSERT INTO @tCalendarHours
SELECT RequestedFor,MeetingType,RoomName,@StartHour FROM @tCalendar WHERE StartTime = @StartTime AND EndTime = @EndTime
SET @StartHour = @StartHour + 1
END
DELETE @tCalendar WHERE StartTime = @StartTime AND EndTime = @EndTime
END