tableOrg

0

Please login or register to vote for this query.

(click on this box to dismiss)

Gardening and Landscaping

Q&A for gardeners and landscapers

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;


--select * From 

/*
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;
*/

Enter Parameters

Options:
Switch to meta site
loading Hold tight while we fetch your results