Hi there.
Use the SqlParamterCollection.Add() method, as given in this example. You can still call the T-SQL as a text command, but you can add paramters to the SQL.
sqlCmd.CommandType = CommandType.Text;
sqlCmd.CommandText = string.Format("UPDATE MyTable SET {0} = @fieldvalue WHERE id = @id", Request.QueryString["fieldname"]);
sqlCmd.Parameters.Add("@fieldvalue", SqlDbType.VarChar).Value = "Some Value";
sqlCmd.Parameters.Add("@id", SqlDbType.Int).Value = "34";
You can also specify the size of the parameter, which is handy for string params.
sqlCmd.Parameters.Add("@fieldvalue", SqlDbType.VarChar, 10).Value = "Some Value";
So anyone trying to put a cheeky SQL statement into the @fieldValue param woudl be hindered by the max 10 chars allowed for the value. This can help limit the possibility of SQL injection attacks. Here's a good link regards SQL injection and .NET code.
In response to comment I got, you might want to verify the request querystring parameter, in case it contains potentially harmful SQL:
string fieldName = HttpUtility.UrlDecode(Request.QueryString["fieldname"]);
if (!fieldName.Contains(" "))
{
// Do the rest of the sql code here...
}
So the idea is, if the parameter has a space, then it can't be a valid field name, so could potentially contain dangerous SQL.
Jas.