The following query takes almost 2 minutes to run. I’m dealing with large tables yet even after indexing still takes too long. Any suggestions will be greatly appreciated (execute plan below)
DECLARE @FromDate datetime
DECLARE @ToDate datetime
DECLARE @SSNumber int
SET @FromDate = '2023-03-01'
SET @ToDate = '2023-07-01'
SET @SSNumber = -1
DECLARE @CareDates TABLE(CareDate datetime, DOW varchar(20))
DECLARE @curDate datetime
DECLARE @curDOW varchar(20)
SET @curDate = @FromDate
WHILE DATEDIFF(day, @curDate, @ToDate + 1) > 0
BEGIN
SET @curDOW = DATENAME(dw, @curDate)
INSERT INTO @CareDates (CareDate, DOW) VALUES (@curDate, @curDOW)
SET @curDate = DATEADD(day, 1, @curDate)
PRINT DATEDIFF(day, @curDate, @ToDate)
END;
WITH personal_care AS
(
SELECT PersonalCareID, SSNumber, ItemCode, CareSchedule, IsCurrent, StartDate
, DATEADD(DAY, -1, (ISNULL(LEAD(StartDate,1) OVER (
PARTITION BY SSNumber, ItemCode
ORDER BY SSNumber, ItemCode, StartDate), '9999-12-31'))) AS EndDate
FROM HOMEResidentPersonalCare
)
SELECT PC.PersonalCareID,
CD.CareDate,
CD.DOW,
PC.SSNumber,
PC.ItemCode,
PC.CareSchedule,
PC.IsCurrent,
PC.StartDate,
PC.EndDate,
PCS.CareScheduleID,
PCS.[Shift],
PCS.EmployeeID,
HRPCP.CareProvidedID,
ISNULL(HRPCP.Status,'I') AS CareStatus
FROM @CareDates CD
CROSS JOIN personal_care PC
INNER JOIN HomeResidentPersonalCareSchedule PCS ON PCS.PersonalCareID = PC.PersonalCareID AND (PCS.DayOfWeek = CD.DOW OR PCS.DayOfWeek = 'All')
LEFT JOIN HomeResidentPersonalCareProvided HRPCP ON HRPCP.CareTypeID = PC.ItemCode AND HRPCP.SSNumber = PC.SSNumber AND HRPCP.[Shift] = PCS.[Shift] AND HRPCP.CareDate = CD.CareDate
WHERE CD.CareDate BETWEEN PC.StartDate AND PC.EndDate
AND (HRPCP.Status IS NULL OR HRPCP.Status <> 'D')
Execution Plan
Tried indexing the tables, rebuilding indexes, rewording the query.
New contributor
romrom72 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.