Q&A for anime and manga fans
CREATE table #yourtable ([Id] int, [Value] varchar(6), [ColumnName] varchar(13)) ; INSERT INTO #yourtable ([Id], [Value], [ColumnName]) VALUES (1, 'John', 'FirstName'), (2, '2.4', 'Amount'), (3, 'ZH1E4A', 'PostalCode'), (4, 'Fork', 'LastName'), (5, '857685', 'AccountNumber') ; --DECLARE -- @tableOrgNum TABLE(id int identity(1,1), [Organization_description] varchar(100)); CREATE table #tableOrgNum (id int identity(1,1) not null,[Organization_description] varchar(100)); INSERT INTO #tableOrgNum ([Organization_description]) select [value] from STRING_SPLIT('PKS Inc*Kiewit Corporation*Infrastructure*Infrastructure West*Infrastructure West (SVP Level)*Western Canada*General - Closed Jobs', '*') where rtrim([value])<>''; DECLARE @cols AS NVARCHAR(MAX), @query AS NVARCHAR(MAX); select @cols = STUFF((SELECT ',' + QUOTENAME(id) from #tableOrgNum group by id order by id FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)') ,1,1,'') set @query = N'SELECT ' + @cols + N' from ( select [Organization_description], id from #tableOrgNum ) x pivot ( max([Organization_description]) for id in (' + @cols + N') ) p ' --exec sp_executesql @query; DECLARE @test AS TABLE( id_1 NVARCHAR(MAX), id_2 NVARCHAR(MAX), id_3 NVARCHAR(MAX), id_4 NVARCHAR(MAX), id_5 NVARCHAR(MAX), id_6 NVARCHAR(MAX), id_7 NVARCHAR(MAX)); INSERT INTO @test exec sp_executesql @query; SELECT * FROM @test CREATE table #tableOrgNumA (id int identity(1,1) not null,[Organization_description] varchar(100)); INSERT INTO #tableOrgNumA ([Organization_description]) select [value] from STRING_SPLIT('PKS Inc*Kiewit Corporation*Energy', '*') where rtrim([value])<>''; --DECLARE --@cols AS NVARCHAR(MAX), --@query AS NVARCHAR(MAX); select @cols = STUFF((SELECT ',' + QUOTENAME(id) from #tableOrgNumA group by id order by id FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)') ,1,1,'') set @query = N'SELECT ' + @cols + N' from ( select [Organization_description], id from #tableOrgNumA ) x pivot ( max([Organization_description]) for id in (' + @cols + N') ) p ' --exec sp_executesql @query; DECLARE @testA AS TABLE( id_1 NVARCHAR(MAX), id_2 NVARCHAR(MAX), id_3 NVARCHAR(MAX)); INSERT INTO @testA exec sp_executesql @query; SELECT id_1, id_2, id_3, id_1 AS [id_4], id_1 AS [id_5], id_1 AS [id_6], id_1 AS [id_7] FROM @testA UNION ALL SELECT * FROM @test