Table name and table field on SqlParameter C#?

提问者:

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

 

 

回答者:

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.

 

提问者:

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

 

回答者:

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.

 

If you are worried about SQL injection, the SqlCommandBuilder class (and other DB specific versions of DbCommandBuilder) have a function called QuoteIdentifier that will escape your table name properly.

var builder = new SqlCommandBuilder(); 
string escTableName = builder.QuoteIdentifier(tableName); 

Now you can used the escaped value when building your statement and not have to worry about injection- but you should still be using parameters for any values.

 

本文来自:http://stackoverflow.com/questions/3128582/table-name-and-table-field-on-sqlparameter-c

你可能感兴趣的:(ADO.NET,table,parameters,sql,sqlserver,tsql,sql,server)