【发布时间】:2012-01-19 12:37:31
【问题描述】:
我正在尝试重构 ASP.Net 网站中的一些代码,但我正在编写的存储过程出现问题。
我想要做的是获取一个日期范围,然后从表格中选择该范围内的所有数据,但是如果日期不存在,我仍然需要选择一行。
正如您在下面的代码中看到的那样,我的想法是创建一个临时表,并用我的日期范围内的所有日期填充它,然后将其加入我从中选择的表中,但这不起作用。我在这里做错了吗?在此连接中 tempDate 列始终为空,但是我检查了该表,其中肯定有数据。
-- Parameters
DECLARE @DutyDate datetime='2012-01-01 00:00:00'
DECLARE @InstructorID nvarchar(2) = N'29'
DECLARE @datesTBL TABLE (tempDate DATETIME)
-- Variables
DECLARE @StartDate DATETIME
DECLARE @EndDate DATETIME
SELECT
@StartDate =StartDate,
@EndDate = EndDate
FROM
DutyPeriodTbl
WHERE
(StartDate <= @DutyDate)
AND
(EndDate >= @DutyDate)
DECLARE @d DATETIME = @StartDate
WHILE @d<=@EndDate
BEGIN
INSERT INTO @datesTBL VALUES (CONVERT(DATETIME, @d, 102))
SET @d=DATEADD(day,1,@d)
END
SELECT
dt.tempDate ,
InstructorID, EventStart,
EventEnd, cancelled,
cancelledInstructor,
EventType, DevName,
Room, SimLocation,
ClassLocation, Event,
Duration, TrainingDesc,
Crew, Notes,
LastAmended, InstLastAmended,
ChangeAcknowledged, Type,
OtherType, OtherTypeDesc,
CourseType
FROM
OpsInstructorEventsView iv
LEFT OUTER JOIN
@datesTBL dt
ON
CONVERT(DATETIME, iv.EventStart, 102) = CONVERT(DATETIME, dt.tempDate, 102)
WHERE
InstructorID = @InstructorID
AND
EventStart BETWEEN CONVERT(DATETIME, @StartDate, 102) AND CONVERT(DATETIME, @EndDate, 102)
ORDER BY
EventStart
【问题讨论】:
-
一个CTE可以做到这一点,看看stackoverflow.com/questions/5899829/…
标签: sql sql-server-2008 stored-procedures