Dynamic where clause in parameter

后端 未结 3 1329
灰色年华
灰色年华 2020-12-22 14:42

I am currently trying to build up the where clause of an SqlCommand.

something similar to this

myCommand.CommandText = \"SELECT * \" +
          


        
相关标签:
3条回答
  • 2020-12-22 15:22

    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

    • you have a List<WhereField> of fields to include in the WHERE clause
    • and that all clauses are ANDed together
    • and WhereField looks something like this

    public 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();
    
    0 讨论(0)
  • 2020-12-22 15:22

    May be you need

    myCommand.CommandText = "SELECT * " +
                            "FROM TABLE1 WHERE " + 
                            "@whereClause";
    
    0 讨论(0)
  • 2020-12-22 15:38

    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();
    
    0 讨论(0)
提交回复
热议问题