6

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
  • Consider that your Users table is denormalized, hence the solution to your problem would involve resolving the design to fifth normal form. Commented Jul 26, 2010 at 9:33

2 Answers 2

13

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.

Sign up to request clarification or add additional context in comments.

Comments

5

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.

5 Comments

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: now take this string that's been formatted and use it in a call to "sp_executesql" and you have your dynamic SQL.....
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: "dynamic SQL" is dynamic, when you "string together" your SQL command and then call sp_executesql to execute it - that's all
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.