I found the workaround using a loop. The steps followed are as follows:
Create a temporary table to hold initial values.
CREATE TABLE #EMP
(
EMPID VARCHAR(10),
EMPNAME VARCHAR(10),
START_DATE DATE,
END_DATE DATE
);
Insert initial values.
INSERT INTO #EMP
SELECT '1001', 'Shivansh', '2015-09-01', '2018-03-31';
INSERT INTO #EMP
SELECT '1004', 'Mayank', '2019-04-01', '2020-06-30';
Create the required table.
CREATE TABLE #NEWEMP
(
EMPID VARCHAR(10),
EMPNAME VARCHAR(10),
START_DATE DATE,
END_DATE DATE
);
Insert the first year date (i.e. if the START_DATE for a tuple is 2015-09-01 insert 2015-09-01 for START_DATE and 2015-12-31 for the END_DATE).
INSERT INTO #NEWEMP
SELECT EMPID, EMPNAME, START_DATE, DATEFROMPARTS(YEAR(START_DATE), 12, 31) FROM #EMP;
Similarly, Insert the last year date.
INSERT INTO #NEWEMP
SELECT EMPID, EMPNAME, DATEFROMPARTS(YEAR(END_DATE), 1, 1), END_DATE FROM #EMP;
Run a while loop till the maximum value of the difference between START_DATE and END_DATE column.
DECLARE @counter INT = 1;
DECLARE @len INT = (SELECT MAX(DATEDIFF(YEAR, START_DATE, END_DATE)) FROM #EMP);
WHILE @counter < @len
BEGIN
INSERT INTO #NEWEMP
SELECT EMPID, EMPNAME, DATEFROMPARTS(YEAR(START_DATE) + @counter, 1, 1), DATEFROMPARTS(YEAR(START_DATE) + @counter, 12, 31) FROM #EMP
WHERE @counter < DATEDIFF(YEAR, START_DATE, END_DATE);
SET @counter += 1;
END
Query the output.
SELECT * FROM #NEWEMP ORDER BY START_DATE;
Here is the Query, written in Azure Synapse Analytics.
The required output is.
