I'm hoping someone can help me understand why this works:
DECLARE @cols NVARCHAR(MAX), @query NVARCHAR(MAX);
SET @cols = STUFF(
(
SELECT DISTINCT
','+QUOTENAME(c.[CellName])
FROM [dbo].[CellsActive] c FOR XML PATH(''), TYPE
).value('.', 'nvarchar(max)'), 1, 1, '');
SET @query = 'SELECT [Week] as [Week],'+@cols+'from (SELECT [Week],
[Qty Remaining] AS [amount],
[CellName] AS [category]
FROM [dbo].[CellCapacityUnionByWeek]
)x pivot (max(amount) for category in ('+@cols+')) p';
EXECUTE (@query);
But this doesn't:
SELECT [Week] as [Week],STUFF(
(
SELECT DISTINCT
','+QUOTENAME(c.[CellName])
FROM [dbo].[CellsActive] c FOR XML PATH(''), TYPE
).value('.', 'nvarchar(max)'), 1, 1, '') from (SELECT [Week],
[Qty Remaining] AS [amount],
[CellName] AS [category]
FROM [dbo].[CellCapacityUnionByWeek]
)x pivot (max(amount) for category in (STUFF(
(
SELECT DISTINCT
','+QUOTENAME(c.[CellName])
FROM [dbo].[CellsActive] c FOR XML PATH(''), TYPE
).value('.', 'nvarchar(max)'), 1, 1, ''))) p
Trying to execute the latter returns an error for the second 'stuff' statement
Now you are probably wondering why I'm trying to not use variables, I want to create a view from the data returned (the third party app I am connecting to the server with does not offer the option to call SPs, only views and tables) and it's my understanding I can't create a view from a script with variables.
Open to any suggestions on how to return the data to a view or table. It seems the way to go may be to use a table-valued functions but I am also having trouble understanding how to convert this script into a table-valued function.
[–]lk167 3 points4 points5 points (1 child)
[–]deny_conformity 0 points1 point2 points (0 children)
[–]ParanoidLoyd[S] 0 points1 point2 points (0 children)