• Do you get the fixed number of columns as output everytime you execute [SP_LogView2]

    --- If Yes, You can have a permanent table with those many column (you can truncate eachtime you execute)

    -- If No, you can change the final query like

    SET @query = '

    SELECT * into FinalCols

    FROM #FirstSplit

    PIVOT

    (

    MAX([Value])

    FOR [Key]

    IN (' + @columns + ')

    )

    AS p

    Now, you can drop this table (FinalCols) everytime from calling proc or in the [SP_LogView2]

    itself.

    Since this is permanent table, you can get all the column names dynamically from using syscolumns table...