views:

34

answers:

2

Hi, Is there any way how to do that? This does not work:

SqlCommand command = new SqlCommand("SELECT @slot FROM Users WHERE name=@name; ");
prikaz.Parameters.AddWithValue("name", name);
prikaz.Parameters.AddWithValue("slot", slot);

The only thing I can think of is to use SP and declare and set the variable for the column. Seems to me a bit ackward.

+1  A: 

You cannot do this in regular SQL - if you must have configurable column names (or table name, for that matter), you must use dynamic SQL - there is no other way to achieve this.

string sqlCommandStatement =  
   string.Format("SELECT {0} FROM dbo.Users WHERE name=@name", "slot");

and then use the sp_executesql stored proc in SQL Server to execute that SQL command (and specify the other parameters as needed).

Dynamic SQL has its pros and cons - read the ultimate article on The Curse and Blessings of Dynamic SQL expertly written by SQL Server MVP Erland Sommarskog.

marc_s
The example code you give above doesn't demonstrate dynamic SQL, it just shows the use of the string.Format function. As written it's confusing.
Yellowfog
@Yellowfog: now take this string that's been formatted and use it in a call to "sp_executesql" and you have your dynamic SQL.....
marc_s
Well, you have your SQL, but it's not particularly 'dynamic', is my point. As I understand this, it refers to SQL which is constructed on the database side of things, not the webserver side. Or am I unusual in taking the term that way?
Yellowfog
@Yellowfog: "dynamic SQL" is dynamic, when you "string together" your SQL command and then call `sp_executesql` to execute it - that's all
marc_s
If you look at the actual reading you cite, below the line "There are two main roads to go, and then there are forks and sub-forks" you'll note that your example falls under 1(ii) whereas 2(ii) is the home of dynamic SQL. This corresponds with my understanding of the term.
Yellowfog
A: 

As has been mentioned, you cannot parameterise the fundamental query, so you will have to build the query itself at runtime. You should white-list the input of this, to prevent injection attacks, but fundamentally:

// TODO: verify that "slot" is an approved/expected value
SqlCommand command = new SqlCommand("SELECT [" + slot +
           "] FROM Users WHERE name=@name; ")
prikaz.Parameters.AddWithValue("name", name);

This way @name is still parameterised etc.

Marc Gravell