KyLim KyLim - 1 month ago 9
SQL Question

MS SQL Temporary table looping

Need help on sql looping query

my table :

enter image description here

my expecting output:

enter image description here

I am able to get 1 line only..

declare @ID nvarchar(50) = (select EMP_ID from HRS_WORKFLOW01);


CREATE TABLE #TEMP(EMP_ID NVARCHAR(200),EMP_L1 NVARCHAR(200),EMP_L2 NVARCHAR(200),EMP_L3 NVARCHAR(200),EMP_L4 NVARCHAR(200))
DECLARE @L1 NVARCHAR(50);
DECLARE @L2 NVARCHAR(50);
DECLARE @L3 NVARCHAR(50);
DECLARE @L4 NVARCHAR(50);

SET @L1 = (SELECT L1EmplNo FROM HRS_WORKFLOW01 WHERE EMP_ID =@ID)
INSERT INTO #TEMP (EMP_ID,EMP_L1)VALUES(@ID,@L1)

SET @L2 = (SELECT L1EmplNo FROM HRS_WORKFLOW01 WHERE EMP_ID =@L1)
UPDATE #TEMP SET EMP_L2=@L2 WHERE EMP_ID=@ID

SET @L3 = (SELECT L1EmplNo FROM HRS_WORKFLOW01 WHERE EMP_ID =@L2)
UPDATE #TEMP SET EMP_L3=@L3 WHERE EMP_ID=@ID

SET @L4 = (SELECT L1EmplNo FROM HRS_WORKFLOW01 WHERE EMP_ID =@L3)
UPDATE #TEMP SET EMP_L4=@L4 WHERE EMP_ID=@ID

SELECT * FROM #TEMP

Answer

You need to use Recursive CTE

;WITH DATA
     AS (SELECT *
         FROM   (VALUES ('ALI','ABU'),
                        ('JOSH','LIM'),
                        ('JAMES','KAREN'),
                        ('LIM','JERRY'),
                        ('JERRY','GEM')) TC(EMP_ID, EMP_L1)),
     REC_CTE
     AS (SELECT EMP_ID,
                EMP_L1,
                Cast(EMP_L1 AS VARCHAR(8000)) AS PARENT,
                LEVEL = 1
         FROM   DATA
         UNION ALL
         SELECT D.EMP_ID,
                D.EMP_L1,
                Cast(RC.PARENT + '.' + D.EMP_L1 AS VARCHAR(8000)),
                LEVEL = LEVEL + 1
         FROM   DATA D
                JOIN REC_CTE RC
                  ON RC.EMP_ID = D.EMP_L1)
SELECT TOP 1 WITH TIES EMP_ID,
                       EMP_L1 = COALESCE(Parsename(PARENT, 1), ''),
                       EMP_L2 = COALESCE(Parsename(PARENT, 2), ''),
                       EMP_L3 = COALESCE(Parsename(PARENT, 3), ''),
                       EMP_L4 = COALESCE(Parsename(PARENT, 4), '')
FROM   REC_CTE
ORDER  BY Row_number()OVER(PARTITION BY EMP_ID ORDER BY LEVEL DESC) 
OPTION (MAXRECURSION 0)

Result :

╔════════╦════════╦════════╦════════╦════════╗
║ EMP_ID ║ EMP_L1 ║ EMP_L2 ║ EMP_L3 ║ EMP_L4 ║
╠════════╬════════╬════════╬════════╬════════╣
║ ALI    ║ ABU    ║        ║        ║        ║
║ JAMES  ║ KAREN  ║        ║        ║        ║
║ JERRY  ║ GEM    ║        ║        ║        ║
║ JOSH   ║ LIM    ║ JERRY  ║ GEM    ║        ║
║ LIM    ║ JERRY  ║ GEM    ║        ║        ║
╚════════╩════════╩════════╩════════╩════════╝

Note : This considers there can be maximum of 4 levels. To split the data into different columns I have used PARSENAME function which will not work if you more then 4 levels.

If you dont want to split the parents into different columns remove the PARSENAME and select the PARENT column alone.

Comments