If a package is shown as leaving the warehouse when the warehouse is not available (between its working hours) then the package's leave date should be the next day right when the warehouse's program starts.
Below is the code that needs reviewing. This code is from a procedure that is called with multiple parameters including warehouses. The warehouse parameter is under this form: "5, 45".
There are multiple deposits with different opening and closing hours. I am using "TOP(1)" for my SELECTS which is a problem as this will only take the opening and closing hours of the first warehouse listed thus assuming that all warehouses have the same schedule.
My question: any ideas to replace the "TOP(1)"?
Code:
WITH CTE AS (
SELECT LeaveDate = CASE
WHEN CAST(LeaveDateTBL.LeaveDate AS time)
BETWEEN (
SELECT TOP(1) dbo.tblAdmPartners_Schedule.WorkStartTime
FROM dbo.tblAdmPartners_Schedule WITH (NOLOCK)
WHERE dbo.tblAdmPartners_Schedule.IdAdmPartner = (
SELECT TOP(1) dbo.tblAdmWarehouses.IdAdmPartner
FROM dbo.tblAdmWarehouses WITH (NOLOCK)
JOIN dbo.tblAdmWarehouses_Aliases WITH (NOLOCK)
ON dbo.tblAdmWarehouses.Id = dbo.tblAdmWarehouses_Aliases.IdAdmWarehouse
) ) AND (
SELECT TOP(1) dbo.tblAdmPartners_Schedule.WorkStopTime
FROM dbo.tblAdmPartners_Schedule WITH (NOLOCK)
WHERE dbo.tblAdmPartners_Schedule.IdAdmPartner = (
SELECT TOP(1) dbo.tblAdmWarehouses.IdAdmPartner
FROM dbo.tblAdmWarehouses WITH (NOLOCK)
JOIN dbo.tblAdmWarehouses_Aliases WITH (NOLOCK)
ON dbo.tblAdmWarehouses.Id = dbo.tblAdmWarehouses_Aliases.IdAdmWarehouse
) )
THEN (LeaveDateTBL.LeaveDate)
ELSE
(DATEADD(DAY, 1, leaveDateTBL.LeaveDate))
END