tags:

views:

63

answers:

2

Hello.

I would like to know how to pass the table name and a table field name via SqlCommand on C#.

Tryied to do it the way it's done by setting the SqlCommand with the @ symbol but didn't work. Any ideas??

+2  A: 

SqlCommand parameters can only be used to pass data. You cannot use them to modify the sql statement (such as adding additional fields to a select statement). If you need to modify the sql statement, I would suggest using a StringBuilder to create the tsql statement.

To elaborate further, .Net does not concatenate the sql before sending it to SqlServer (at least not in the straight-forward way you might expect). It actually calls a stored procedure and passes the arguments in separately. This allows Sql Server to cache the query plan and optimize the performance of you tsql.

If you were to write this SqlCommand...

var cmd = new SqlCommand("SELECT * FROM MyTable WHERE MyID = @MyID", conn);
cmd.Parameters.AddWithValue("@MyID", 1);
cmd.ExecuteNonQuery();

This is the tsql that is issued to Sql Server...

exec sp_executesql N'SELECT * FROM MyTable WHERE MyID = @MyID',N'@MyID int',@MyID=1

You can read more about sp_executesql on MSDN.

Brian
Thanks... as I suposed :) already did a "trick" with a String Builder, but worries me the SQL Injection
Jean Paul
You should still use a SqlCommand with parameters for the values. If you are allowing users to type in the fields then just make sure that the field names are valid (at least only contain valid characters) before adding them to the sql.
Brian
+2  A: 

I guess you are trying to execute a sql statement like

select @field from @table

but that will not work. Sql can't have parameters on fieldnames or tablenames, just on values.

If my guess wasn't correct, please extens your question.

Hans Kesting
Thanks... as I suposed :) already did a "trick" with a String Builder, but worries me the SQL Injection
Jean Paul