How can I phrase this SQL command?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Alex Dransfield
    New Member
    • Jan 2011
    • 46

    How can I phrase this SQL command?

    I am having trouble with writing this SQL command. Basically, I have 4 checkboxes on my form and I want to populate a DataGridView depending on how the checkboxes are ticked. The user can have 0, 1, 2, 3 or all 4 of the checkboxes ticked, meaning that I have 15 different commands to write (if my maths is correct).

    For example...

    Code:
    if(ocrChecked and aqaChecked)
    {
    sqlCommand = "...";
    }
    or...

    Code:
    if(ocrChecked and edexcelChecked)
    {
    sqlCommand = "...";
    }
    .

    If you don't understand what I mean then I will try to explain it better, but in the mean time if anyone has any suggestions on how I could do this without having to do it inefficiently then please let me know.

    By inefficient, I mean that I would have to do...
    Code:
    if(a b c d)
    if(a b c)
    if(a b d)
    if(a d c)
    if(b c d)
    if(a b)
    if(a c)
    if(a d)
    if(b c)
    if(b d)
    if(c d)
    if(a)
    if(b)
    if(c)
    if(d)
    Thanks!
  • hype261
    New Member
    • Apr 2010
    • 207

    #2
    In these situations I just dynamically create the SQL command to execute. So for 4 check boxes you would do something like this.

    Code:
    string sql = "Select * FROM SomeTable ";
    string where = "WHERE "
    
    if(a)
    {
    where = where + " Something = true AND "
    }
    
    if(b)
    {
    where = where + " SomethingElse = true AND "
    }
    
    ... Other check boxes
    
    //check to see if any of the check boxes were true
    if(where.Length > 6)
    {
    //remove the last AND from the string
    where.Remove(where.Length - 5);
    
    sql = sql + where;
    }
    Hope this helps

    Comment

    Working...