I am currently trying to build up the where clause of an SqlCommand
.
something similar to this
myCommand.CommandText = \"SELECT * \" +
It seems you're trying to add the entire WHERE clause as a parameter - that won't work!
So suppose you need to build something like this
SELECT * from TABLE1 WHERE Field1=@Field1Value and Field2=@Field2Value
And assuming
List<WhereField>
of fields to include in the WHERE clauseWhereField
looks something like thispublic class WhereField
{
public string FieldName{get;set;}
public object FieldValue{get;set;}
public string ComparisonOperator{get;set;}
}
then you have something like this:
var whereClause = new StringBuilder();
foreach (var field in WhereFields)
{
whereClause.Append(field.FieldName)
.Append(field.ComparisonOperator)
.Append("@")
.Append(field.FieldName).Append("Value")
.Append (" AND ");
//add the parameter as well:
myCommand.Parameters.AddWithValue("",field.FieldName+"Value");
}
//cleanly close the where clause
whereClause.Append("1=1");
And now you can execute
myCommand.CommandText = "SELECT * " +
"FROM TABLE1 WHERE " + whereClause.ToString();
May be you need
myCommand.CommandText = "SELECT * " +
"FROM TABLE1 WHERE " +
"@whereClause";
You can't use a clause (where) with parameters, you are only allowed to use parameters with command.Parameters
.
To build a dynamic Where clause, you have to build your query based on conditions and string concatenation and then add the parameters accordingly.
Something like:
sb.Append("SELECT * FROM TABLE1 ");
if (someCondition)
{
sb.Append("WHERE XColumn = @XColumn");
myCommand.Parameters.AddWithValue("@XColumn", "SomeValue");
}
else
{
sb.Append("WHERE YColumn = @YColumn");
myCommand.Parameters.AddWithValue("@YColumn", "SomeOtherValue");
}
myCommand.CommandText = sb.ToString();