I want to keep the column names generated by @columnsToPivot intact when building my dynamic SQL query.
Below is my @columnsToPivot
query
DECLARE @columnsToPivot AS NVARCHAR(MAX);
DECLARE @pivotQuery AS NVARCHAR(MAX);
SELECT @columnsToPivot = STRING_AGG(QUOTENAME([QuestionaireId]) + ', ' + QUOTENAME('Response'), ',')
FROM (
SELECT DISTINCT [QuestionaireId]
FROM [prod].[CCRS_Audit]
) AS QIDS;
The output of the above query is the modified columns names
[23]Response, [43]Response, [56]Response
When I am using the above query to generate the dynamic query, Its removing the QuestionaireId's and only keeping Response as the column name. Below is the query
SET @pivotQuery = '
SELECT CaseId,
Auditor,
FormName,
[Organization],
[Accession Number],
' + @columnsToPivot + '
FROM (
SELECT CaseId,
Auditor,
FormName,
[Organization],
[AccessionNumber],
[QuestionaireId],
[Response]
FROM [prod].[CCRS_Audit]
) AS SourceTable
PIVOT (
MAX(Response) FOR QuestionaireId IN (' + @columnsToPivot + ')
) AS PivotTable';
';
EXEC sp_executesql @pivotQuery;
The output of the above query is
Response, Response, Response
But I want the output should be in the below format
23Response, 43Response, 53Response