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??
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??
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.
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.