DECLARE @overview TABLE(
category VARCHAR(50)
)
INSERT INTO @overview
SELECT DISTINCT category
FROM table_3
DECLARE @temp_table TABLE(
category VARCHAR(100),
increment IDENTITY(1,1)
)
INSERT INTO @temp_table
SELECT DISTINCT category
FROM table_1
DECLARE @cursor INT
SET @cursor = 2
DECLARE @cursor_max INT
SET @cursor_max = (
SELECT MAX(increment)
FROM @temp_table
)
DECLARE @top_cat VARCHAR(100)
SET @top_cat = (
SELECT TOP(1) category
FROM @temp_table
)
DECLARE @select_module NVARCHAR(MAX)
SET @select_module = CONCAT(
'subfunction, [',@top_cat,']'
)
DECLARE @join_module NVARCHAR(MAX)
SET @join_module = CONCAT(
'
LEFT JOIN (
SELECT SUM(table_2.totals) [',
(SELECT @top_cat,'],
table_2.description
WHERE table_2.category = ',
(SELECT @top_cat),'
GROUP BY table_2.description
) AS join_',@cursor,'
ON join_',@cursor,'.description = oo.function'
)
WHILE @cursor <= @cursor_max
BEGIN
SET @select_module = CONCAT(
@select_module,', [',(SELECT category from @temp_table WHERE increment = @cursor),']'
)
SET @join_module = CONCAT(
@join_module,'
LEFT JOIN (
SELECT SUM(table_2.totals) [',
(SELECT category from @temp_table WHERE increment = @cursor),'],
table_2.description
WHERE table_2.category = ',
(SELECT category from @temp_table WHERE increment = @cursor),'
GROUP BY table_2.description
) AS join_',@cursor,'
ON join_',@cursor,'.description = oo.function'
)
SET @cursor += 1
END
DECLARE @instruction NVARCHAR(MAX)
SET @instruction = CONCAT(
'SELECT ',@select_module,'
FROM ',@overview ,'oo
',@join_module
)
EXEC sp_executesql @instruction
The code above gives the following errors:
Must declare the table variable "@overview".
Incorrect syntax near 'Line'.
Incorrect syntax near the keyword 'AS'.
Incorrect syntax near the keyword 'Full'.
I think the errors are coming from string formatting, but I can't place where any mistakes are. I'm trying to join multiple columns onto the table @overview, using the @cursor and while loop to iterate through @temp_table to find the columns to join, and then the @select_module, @join_module, and @instruction to build the final statement. Any help would be really appreciated