Hi @Akshay Chavan
Check this:
DECLARE @Count INT =1
DECLARE @Sql_String VARCHAR(MAX) =
';WITH CTE1 AS
(SELECT FolioKey,col1,col2,col3,ApkKey,col5,col6,col7,col8,col9
,data'+CAST((@Count-1)*5+1 AS VARCHAR(20))+'
,data'+CAST((@Count-1)*5+2 AS VARCHAR(20))+'
,data'+CAST((@Count-1)*5+3 AS VARCHAR(20))+'
,data'+CAST((@Count-1)*5+4 AS VARCHAR(20))+'
,data'+CAST((@Count-1)*5+5 AS VARCHAR(20))+'
FROM TestTable WHERE RowNm=1)'
--PRINT @Sql_String
WHILE (SELECT COUNT(*) FROM TestTable WHERE RowNm = @Count + 1) > 0
BEGIN
SET @Sql_String=@Sql_String+
',CTE'+CAST(@Count+1 AS VARCHAR(20))+'
AS(SELECT C.*,T.data1 AS data'+CAST((@Count)*5+1 AS VARCHAR(20))+'
,T.data2 AS data'+CAST((@Count)*5+2 AS VARCHAR(20))+'
,T.data3 AS data'+CAST((@Count)*5+3 AS VARCHAR(20))+'
,T.data4 AS data'+CAST((@Count)*5+4 AS VARCHAR(20))+'
,T.data5 AS data'+CAST((@Count)*5+5 AS VARCHAR(20))+'
FROM CTE'+CAST(@Count AS VARCHAR(20))+' C LEFT JOIN TestTable T ON C.ApkKey=T.ApkKey AND T.RowNm='+CAST(@Count+1 AS VARCHAR(20))+')'
SET @Count= @Count + 1
END
SET @Sql_String=@Sql_String+'SELECT * FROM CTE'+CAST(@Count AS VARCHAR(20))+''
PRINT @Sql_String
EXEC (@Sql_String)
Best regards,
LiHong
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our Documentation to enable e-mail notifications if you want to receive the related email notification for this thread.