2

I have to write a dynamic pivot based on a complex query and I want to use a common table expression to create the dataset on which I have to build the pivot to keep it outside the dynamic sql and have it compiled

My problem is that I don't know if i can use the CTE in a SET where I wrap the dynamic SQL I have to execute.

let see the code:

WITH DatiCTE AS
    (
    SELECT ...
    )

    SET @DynamicPivotQuery = 
          N'SELECT IdActivity, ' + @PivotSelectColumnNames + '
    FROM DatiCTE
    PIVOT(SUM(NumOfDays) 
          FOR Area IN (' + @PivotColumnNames + ')) AS PVTTable'
          WHERE 1 = 1

EXEC sp_executesql @DynamicPivotQuery

This way i get an error near SET @DynamicPivotQuery =

If I replace SET with a SELECT the stored procedure is compiled but if i run it I get:

Invalid object name 'DatiCTE'

2 Answers 2

4

Move the definition of the CTE WITH DatiCTE AS to be inside the dynamic sql like this:

SET @DynamicPivotQuery = 
  N'WITH DatiCTE AS
    (
       SELECT ...
    )
    SELECT IdActivity, ' + @PivotSelectColumnNames + '
    FROM DatiCTE
    PIVOT(SUM(NumOfDays) 
      FOR Area IN (' + @PivotColumnNames + ')) AS PVTTable'
      + 'WHERE 1 = 1';

EXEC sp_executesql @DynamicPivotQuery;
Sign up to request clarification or add additional context in comments.

2 Comments

the scope of the CTE is to keep the costant code outside of the dynamic SQL
Why is this answer upvoted? It does not work.
2

for now i switch to temp table:

SELECT ...
INTO @TempTable

SET @DynamicPivotQuery = 
  N'
    SELECT IdActivity, ' + @PivotSelectColumnNames + '
    FROM @TempTable
    PIVOT(SUM(NumOfDays) 
      FOR Area IN (' + @PivotColumnNames + ')) AS PVTTable'
      + 'WHERE 1 = 1';

EXEC sp_executesql @DynamicPivotQuery;

but i have soume doubt about concurrent users. i try table variable but cant be used in dynamic sql...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.