Are you looking for the below:
CREATE TABLE customer(name VARCHAR(25), class VARCHAR(25) , id Varchar(25) ,product1 VARCHAR(25)) INSERT INTO customer VALUES('A','x',1, 'L') INSERT INTO customer VALUES('B','y',2, 'M') INSERT INTO customer VALUES('C','z',3, 'N') INSERT INTO customer VALUES('D','u',4, 'O') sELECT * fROM customer Create Table #Temp_Intermediate(Attribute Varchar(10),AttributeValue Varchar(500)) declare @SQL varchar(max) = '' set @SQL = 'select attribute,attributevalue from (Select * From customer SA)a unpivot (AttributeValue for Attribute in ('+ stuff((select ','+quotename(C.name) from sys.columns as C where C.object_id = object_id('customer') and C.name in( 'name','class','id','product1') for xml path('')), 1, 1, '')+ N')) as U ' print @SQL Insert into #Temp_Intermediate exec (@SQL) ;WITH L0 AS(SELECT 1 AS c UNION ALL SELECT 1), L1 AS(SELECT 1 AS c FROM L0 AS A, L0 AS B), L2 AS(SELECT 1 AS c FROM L1 AS A, L1 AS B), L3 AS(SELECT 1 AS c FROM L2 AS A, L2 AS B), Numbers AS(SELECT ROW_NUMBER() OVER(ORDER BY c) AS n FROM L3) SELECT attribute, [1] AS Column1, [2] AS Column2, [3] AS Column3, [4] AS Column4 FROM (SELECT attribute, ROW_NUMBER() OVER (PARTITION BY attribute ORDER BY nums.n) AS PositionInList, LTRIM(RTRIM(SUBSTRING(valueTable.attributevalues, nums.n, charindex(N',', valueTable.attributevalues + N',', nums.n) - nums.n))) AS [Value] FROM Numbers AS nums INNER JOIN (SELECT Rid.attribute, STUFF(g.y, 1, 1, '') AS attributevalues FROM ( SELECT attribute FROM #Temp_Intermediate GROUP BY attribute ) AS Rid CROSS APPLY ( SELECT DISTINCT ',' + AttributeValue FROM #Temp_Intermediate AS s WHERE s.Attribute = Rid .Attribute ORDER BY ',' + AttributeValue FOR XML PATH('')) AS g ( y ) ) AS valueTable ON nums.n <= CONVERT(int, LEN(valueTable.attributevalues)) AND SUBSTRING(N',' + valueTable.attributevalues, n, 1) = N',') AS SourceTable PIVOT ( MAX([VALUE]) FOR PositionInList IN ([1], [2], [3], [4]) )as table2 Drop table customer Drop table #Temp_Intermediate
Please click the Mark as Answer or Vote As Helpful button if a post solves your problem or is helpful!