Sorry for the long question but this contains all the SQL I\'ve used to test the scenario to hopefully make it clear as to what I\'m doing.
I\'m build up some dynami
We've done a lot of work similar to your example. We haven't worried about SQL injenction, in part because we have complete and total control over the data being pivoted--there's just no way malicious code could get through ETL into our data warehouse.
Some thoughts and advice:
Hah. It took writing all that to remember function QUOTENAME(). A quick test would seem to indicate that adding it to your code like so would work (You'll get an error, not a dropped temp table):
SELECT
@columns =
STUFF
(
(
SELECT DISTINCT
', [' + quotename(ColumnB, ']') + ']'
FROM
#PivotTest
FOR XML PATH('')
), 1, 1, ''
)
This should work for pivot (and unpivot) situations, since you almost always have to [bracket] your values.