I have code that splits records on months based on their length, the code currently works without problem, but I need to calculate how many days passed between these new records so I could get something like this:
id  begdate     enddate     days newbeg      newend      
---------------------------------------------------------
123 03/04/2018  03/05/2018  31   03/04/2018  30/04/2018  
123 03/04/2018  03/05/2018  31   01/04/2018  03/04/2018  
What I need to display
id  begdate     enddate     days newbeg      newend      days2
---------------------------------------------------------------
123 03/04/2018  03/05/2018  31   03/04/2018  30/04/2018  28
123 03/04/2018  03/05/2018  31   01/04/2018  03/04/2018   4
In my code I created a CTE taken from here to split rows and on the final select I'm using a DATEDIFF for newbeg and newend but I get an Error 207, Level 16, State 1, Procedure xx because newbeg and newend aren't valid on the table
;WITH n(n) AS
 --first select goes here
(
--SECOND SELECT
)
SELECT
    --COLUMNS FROM ORIGINAL TABLE
    --DISP NEW COL
    BEGDATE = f, ENDDATE = t,
    --SPLITTED COL
    NEWBEG = CASE n WHEN 0  THEN f ELSE bp END,
    NEWEND = CASE n WHEN md THEN t ELSE ep END,
    --CALC NEW PERDIODS WHERE I GET Msg 207
    DATEDIFF(dd, NEWBEG, NEWEND) as DAYS2
FROM 
    d 
WHERE 
    md >= n
ORDER BY 
    BEGDATE, NEWBEG;
Maybe this is not the appropriate approach or I'm doing something wrong, any help is thanked in advance.