SQL Server – Dynamic PIVOT Table – SQL Injection

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:

  • Are you required to pivot with nvarcahr(500) columns? Ours are varchar(25) or numerics, and it would be pretty hard to sneak damaging code in through there.
  • How about data checking? Seems like if one of those strings contained a “]” character, it’s either a hack attempt or data that will blow up on you anyway.
  • How robust is your security? Is the system locked down such that Malorey can’t sneak his hacks into your database (either directly or through your application)?

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.

Leave a Comment