문제

Suppose I want to drop a table, whose name is a variable value, such as "#t".

SqlCommand cmd = new SqlCommand( "drop table " + TableName ); //Not safe
SqlCommand cmd = new SqlCommand( "drop table [" + TableName +"]" ); //Not safe
EXEC( 'drop table [' + @tablename +"]" ); --Not safe

None of the above are safe from SQL injection, so what is the alternative?

People say "you have to use dynamic SQL", but the examples still usually involve unsafe concatenation like the third example above.

The closest thing to an answer I can find (https://stackoverflow.com/a/14026855/88409) basically says you have to do the check yourself, and there's no way around it (i.e. ensure the variable is valid through parsing it or getting it from a trusted source), but I'm not satisfied with that answer.

도움이 되었습니까?

해결책

The QUOTENAME function will make sure your variable is treated as a "valid SQL Server delimited identifier".

It is then up to you to decide if the table given is one they should be allowed to delete. Maybe with SQL permissions on the table or a whitelist of tables that can be deleted...

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top