I have the following code, (based on the community member help):
use [Credible];
WITH DataSource AS
(
SELECT
ROW_NUMBER() OVER(ORDER BY epi.[client_id]) AS [row_id]
,epi.[client_id]
,CONVERT(date, epi.[admission_date]) AS [admission_date]
,CONVERT(date, DATEADD(MONTH, 3, epi.[admission_date])) AS [3Month Date]
,CONVERT(date, ISNULL(epi.[discharge_date], GETDATE())) AS [discharge_date]
FROM
[dbo].[ClientEpisode] epi
WHERE DATEADD(MONTH, 3, [admission_date]) <= ISNULL([discharge_date], GETDATE())
),
RecursiveDataSource AS
(
SELECT
[row_id]
,[client_id]
,[admission_date]
,[3Month Date]
,[discharge_date]
,0 AS [level]
FROM
DataSource
UNION ALL
SELECT
ds.[row_id]
,ds.[client_id]
,ds.[admission_date]
,DATEADD(MONTH, 3, rds.[3Month Date])
,ds.[discharge_date]
,[level] + 1
FROM
RecursiveDataSource rds
INNER JOIN DataSource ds ON
rds.[row_id] = ds.[row_id] AND DATEADD(MONTH, 3, rds.[3Month Date]) < ds.[discharge_date]
)
SELECT *
FROM RecursiveDataSource
ORDER BY [row_id]
,[level]
-- OPTION (MAXRECURSION 32767);
This code works with the speed around 30 sec if there are up to 1 000 records in the table.
But my table is over 14 000 records, and will grow more, and the code works 10+++ min
Is there way to make its performance in 30 sec or so?
Thank you for help