I\'m having a problem. I want this to work, but it doesn\'t:
SqlDataSource.SelectCommand = \"SELECT blah1, blah2 FROM myTable WHERE @ColumnName = @Value\";
SqlD
I'm afraid you can't do that, what you can do instead is a little trick:
SELECT blah1, blah1 FROM myTable
WHERE (@blah1 is null or blah1 = @blah1)
or (@blah2 is null or blah2 = @blah2)
and provide all params @blah1, @blah2 but only assign those you need.
NB solution that Mike Christensen offering you is basically building string with right condition, which in simplest case would be
public bool BuildQueryWithCondition(string fieldName, string fieldValue) {
var queryTemplate = "SELECT blah1, blah1 FROM myTable WHERE {0} = @Value"
, query = string.Format(queryTemplate, fieldName)
SqlDataSource.SelectCommand = query;
SqlDataSource.SelectParameters.Add("Value", System.Data.DbType.String, fieldValue);
}
I have figured out a way to include a work around for parametrized column names. I had the same problem but came up with a different way and since I would be the only one using the column names then I believe this is still a safe bet.
String sqlcomm = "SELECT * FROM Asset WHERE " + assetColName + " = ";
command.CommandText = sqlcomm + "$assetColValue";
//command.CommandText = @"SELECT * FROM Asset WHERE $assetColName = '$assetColValue'";
//command.Parameters.AddWithValue("$assetColName", assetColName);
command.Parameters.AddWithValue("$assetColValue", assetColValue);
As you can see from the code above. I tried almost what you did which I then had to comment out. I then concatenated strings together and was able to use my paramterized column name and value which then the value is securely added. The column name however is not secured but this is a method that only I will be using so its still somewhat safe. You can add regular expressions if you want to be more secure but you get the idea of the fix.
Since query parameters are resolved after the SQL is parsed and an execution plan is generated, you can't actually dynamically build SQL with parameters. I would recommend building the SQL string itself, in a safe way of course. Perhaps first create an enum
of valid column names:
enum DbColumns { One, Two, Three };
And then build the SQL string like so:
DbColumns colName = (DbColumns)Enum.Parse(typeof(DbColumns), "One");
SqlDataSource.SelectCommand = String.Format("SELECT blah1, blah1 FROM myTable WHERE {0} = @Value", colName);
Another idea would be to validate the column name using a regular expression, perhaps only allowing [a-z]
.