Data Expose

0

Please login or register to vote for this query.

(click on this box to dismiss)

Lifehacks

Q&A for people looking to bypass life's everyday problems with simple tricks

CREATE table #yourtable
    ([Id] int, [Value] varchar(10), [ColumnName] varchar(13),[RowId] varchar(13),[Lid] int,[Pid] int)
;
    
INSERT INTO #yourtable
    ([Id], [Value], [ColumnName],[RowId],[Lid],[Pid])
VALUES
    (1, 'John', 'FirstName','E01',1,2),
    (2, '2.4', 'Amount','E01',1,2),
    (3, 'ZH1E4A', 'PostalCode','E01',1,2),
    (4, 'Fork', 'LastName','E01',1,2),
    (5, '857685', 'AccountNumber','E01',1,2),
    (6, 'E01', 'RowId','E01',1,2),
      (7, 'John1', 'FirstName','E011',1,2),
    (8, '2.41', 'Amount','E011',1,2),
    (9, 'ZH1E4A1', 'PostalCode','E011',1,2),
    (10, 'Fork1', 'LastName','E011',1,2),
    (11, '8576851', 'AccountNumber','E011',1,2),
    (12, 'E011', 'RowId','E011',1,2),
  
  (13, 'John', 'LAST_NAME','E01',1,1),
    (14, '24', 'AGE','E01',1,1),
    (15, 'ZH1E4A', 'PostalCode','E01',1,1),
    (16, 'Fork', 'LastName','E01',1,1),
    (17, '857685', 'AccountNumber','E01',1,1),
    (18, 'E01', 'RowId','E01',1,1);
    
    
DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX);
    
DECLARE @PID AS INT;
DECLARE @LID AS INT;
    
 
SET @PID=1;
SET @LID=1;

select @cols = STUFF((SELECT distinct ',' + QUOTENAME(ColumnName) 
                    from #yourtable where ColumnName !='RowId' AND Lid=@LID AND Pid=@PID
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT RowId,' + @cols + '
             from 
             (
                select ColumnName, RowId, Value
                from #yourtable WHERE Lid=@LID AND Pid=@PID
            ) x
            pivot 
            (
                max(Value)
                for ColumnName in (' + @cols + ')
            ) p '
PRINT @query
--execute(@query)
--exec sp_executesql @query;

Enter Parameters

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