I have a stored procedure which does dynamic pivot task. I want the results of this procedure to be loaded into a table. This table either could be emptied/dropped prior to loading.
Here is my code that I used for the task. But I receive the following error.
Dynamic Pivot Error in sql server
Configuration option 'show advanced options' changed from 1 to 1. Run the RECONFIGURE statement to install.
Configuration option 'Ad Hoc Distributed Queries' changed from 1 to 1. Run the RECONFIGURE statement to install.
Msg 11514, Level 16, State 1, Procedure sp_describe_first_result_set, Line 1 The metadata could not be determined because statement 'exec sp_executesql @query;' in procedure 'DynamicPivotProcedure' contains dynamic SQL. Consider using the WITH RESULT SETS clause to explicitly describe the result set
Code:
create procedure dbname.schemaname.DynamicPivotProcedure 
as
begin
DECLARE @cols  AS NVARCHAR(MAX),
        @query AS NVARCHAR(MAX)
SELECT @cols = Stuff((SELECT ',' + Quotename([check])
                      FROM   TEST
                      GROUP  BY [Check]
                      FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
SET @query = N'SELECT ID, [Total Of Score],' + @cols + N' from 
             (SELECT TEST.[ID],
                     Score,
                     [check],
                     [Total Of Score] = Count(TEST.Score) over(partition by [ID], [score], [check])
             FROM TEST) T
            pivot 
            (
             SUM (T.[score])
             for T.[check] in (' + @cols + N') ) p '
EXEC Sp_executesql @query; 
end
go
sp_configure 'Show Advanced Options', 1
GO
RECONFIGURE
GO
sp_configure 'Ad Hoc Distributed Queries', 1
GO
RECONFIGURE
GO
IF OBJECT_ID('tempdb..#MyTempTable') IS NOT NULL 
begin
DROP TABLE #MyTempTable
end
SELECT * INTO #MyTempTable FROM 
OPENROWSET('SQLNCLI', 'Server= ABC124;Trusted_Connection=yes;',
     'EXEC DATABASE.Schemaname.DynamicPivotProcedure')
SELECT * FROM #MyTempTable
 
     
    