Look at your line of code
SET @SQLSTRING = 'DECLARE @RETURN_TABLE TABLE ('+@STATIC_COLUMN+' NVARCHAR(255) NULL,'+@TEMPVARCOLUMNS+')
when you pass
@STATIC_COLUMN
as '[CompanyID]'
@SQLSTRING
will read
DECLARE @RETURN_TABLE ([CompanyID] NVARCHAR(255) NULL ...
That is valid syntax so the code will work.
BUT, now look what happens when you pass
@STATIC_COLUMN
as '[CompanyID],[Year]'.
@SQLSTRING
reads
DECLARE @RETURN_TABLE ([CompanyID], [Year] NVARCHAR(255) NULL ...
No type is defined for
[CompanyID]
and
[Year]
is defined as an NVARCHAR
There are ways around this - you could for example, query the system views for the column list so you know which type each column should be defined as in the declaration of
@RETURN_TABLE
. Personally I think that is making life far too over-complicated.
An alternative is to use a temporary table instead of a table variable, and avoid the need to declare/define the table before running the SQL that will populate it ... i.e replace
SET @SQLSTRING = 'DECLARE @RETURN_TABLE TABLE ('+@STATIC_COLUMN+' NVARCHAR(255) NULL,'+@TEMPVARCOLUMNS+')
INSERT INTO @RETURN_TABLE('+@STATIC_COLUMN+','+@AVAIABLE_TO_PIVOT+')
select * from (
SELECT ' + @STATIC_COLUMN + ' , ' + @PIVOT_COLUMN + ', ' + @VALUE_COLUMN + ' FROM '+@TABLE+' ) a
PIVOT
(
'+@AGGREGATE+'('+@VALUE_COLUMN+')
FOR '+@PIVOT_COLUMN+' IN ('+@AVAIABLE_TO_PIVOT+')
) piv
SELECT * FROM @RETURN_TABLE'
with
SET @SQLSTRING = 'select * from (
SELECT ' + @STATIC_COLUMN + ' , ' + @PIVOT_COLUMN + ', ' + @VALUE_COLUMN + ' INTO #RETURN_TABLE FROM '+@TABLE+' ) a
PIVOT
(
'+@AGGREGATE+'('+@VALUE_COLUMN+')
FOR '+@PIVOT_COLUMN+' IN ('+@AVAIABLE_TO_PIVOT+')
) piv
SELECT * FROM #RETURN_TABLE'
Caveat: I have not tested this so I may have made minor syntactical errors, but hopefully this will give you enough of the principle, and you have data with which to test this, whereas I do not (it's always a good idea to share sample data and expected results)
Once last piece of advice, when creating dynamic SQL always PRINT the derived SQL string and try to run it in an IDE that will generate error messages - it's a lot easier to spot the problems that way