I am building a query where I will need a UNPIVOT on dynamic columns. (abcd are example string name)
data1 data2 com fr random
1 2 a d sq
3 4 b a fd
UNPIVOT like so :
data1 data2 Name Website random
1 2 a com sq
1 2 d fr sq
3 4 b com fd
3 4 a fr fd
The matter here is for building my First table I use dynamic SQL (@QueryFinal) because of the column. Here is my UNPIVOT dynamic Query
'SELECT data1, data2, Name, Website
FROM '+@QueryFinal+'
UNPIVOT (
Name FOR Website in ('+@WebsiteCol+')
) f;'
In my @QueryFinal I have a WHERE .... ORDER BY, it seems like the UNPIVOT can't handle it. When I delete the WHERE and ORDER BY clause I get the error :
Incorrect syntax near the keyword 'UNPIVOT'.