Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Variables as Column names in Where Clause [duplicate]

I need some help with my SQL logic, and I've been working (and researching) this for 2 days now with zero success.

My goal is to try an pass a variable from an ASP page to a stored procedure, which is utilizing the variable as criteria for a column name in the where clause.

So for example (a simplified version of my query):

@strDept nvarchar(10), @strUser nvarchar(30)
-- The asp page will pass f18 to @strDept & Ted Lee to strUser
-- f18 is the column name in my database that I need in the where.

select x, y, z from table1 where @strDept in (@strUser)
-- and this is the select statement, notice the where clause.

The stored procedure does execute, but it returns no values and I know its treating the @strDept as a literal nvarchar and not a column name.

So I guess my question is, how do I get SQL Server 2005 to treat my @sqlDept variable as a column name?

like image 874
SyD Avatar asked Dec 05 '22 09:12

SyD


1 Answers

The reason you can't find guidance on how to do this is that it's a really bad idea.

Sooner or later, someone is going to pass a "column name" of 1 ;drop database badidea. Which will be a blessing for all concerned.

Read up on SQL Injection, and rethink your design.

like image 162
podiluska Avatar answered Dec 21 '22 22:12

podiluska