SQL Server - Dynamic PIVOT Table - SQL Injection

前端 未结 3 1398
攒了一身酷
攒了一身酷 2020-11-27 18:54

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

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-27 19:17

    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.

提交回复
热议问题