Start with a
tally table[
^] containing enough numbers to cover the maximum length of leave. Combine that with
DateAdd
to expand the leave days, and filter out any days beyond the end date of the request.
WITH E1(N) AS
(
SELECT 1
UNION ALL SELECT 1
UNION ALL SELECT 1
UNION ALL SELECT 1
UNION ALL SELECT 1
),
E2(N) AS
(
SELECT 1
FROM E1 a CROSS JOIN E1 b
),
E4(N) AS
(
SELECT 1
FROM E2 a CROSS JOIN E2 b
),
E(N) As
(
SELECT ROW_NUMBER() OVER (ORDER BY N) - 1
FROM E4
)
SELECT
LeaveRequests.EMPNAME,
LeaveRequests.LeaveType,
DateAdd(day, E.N, LeaveRequests.FromDate) As LeaveDate
FROM
LeaveRequests
CROSS JOIN E
WHERE
DateAdd(day, E.N, LeaveRequests.FromDate) <= LeaveRequests.ToDate
;