I am writing a query to pivoting table elements where column name is generated dynamically.
SET @query = N'SELECT STUDENT_ID, ROLL_NO, TITLE, STUDENT_NAME, EXAM_NAME, '+
@cols +
' INTO ##FINAL
FROM
(
SELECT *
FROM #AVERAGES
UNION
SELECT *
FROM #MARKS
UNION
SELECT *
FROM #GRACEMARKS
UNION
SELECT *
FROM #TOTAL
) p
PIVOT
(
MAX([MARKS])
FOR SUBJECT_ID IN
( '+
@cols +' )
) AS FINAL
ORDER BY STUDENT_ID ASC, DISPLAYORDER ASC, EXAM_NAME ASC;'
EXECUTE(@query)
select * from ##FINAL
This query works properly in my local database, but it doesn’t work in SQL Azure since global temp tables are not allowed there.
Now if i change ##FINAL to #FINAL in my local database, but it gives me error as
Invalid object name ‘#FINAL’ .
How can I resolve this issue?
Okay, after saying I didn’t think it could be done, I might have a way. It’s ugly though. Hopefully, you can play with the below sample and adapt it to your query (without having your schema and data, it’s too tricky for me to attempt to write it):
They key is to create the temp table in the outer scope, and then inner scopes (code running within
EXECstatements) have access to the same temp table. The above worked on SQL Server 2008, but I don’t have an Azure instance to play with, so not tested there.