Dynamic where clause in parameter

后端 未结 3 1352
灰色年华
灰色年华 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: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();
    

提交回复
热议问题