Results 1 to 1 of 1

Thread: Using Parameters with an SQL IN Clause

  1. #1

    Thread Starter
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,350

    Using Parameters with an SQL IN Clause

    VB version here.

    Myself and others suggest with regularity that values be inserted into SQL statements using parameters rather than string concatenation. Using parameters is more secure, more readable, less error-prone and negates the need to escape single quotes in text values.

    Using parameters can be a bit tricky with an IN clause though, e.g.
    SQL Code:
    1. SELECT * FROM MyTable WHERE ID IN (3, 10, 17)
    You cannot use a single parameter for the whole list, but if you don't know how many values will be in the list then you can't add the parameters easily.

    The way to work around this is to use a combination of string concatenation and parameters. You build a list of parameter place holders using string concatenation, then add the corresponding parameters to the command.

    As an example, assume you have a ListBox containing possible field values. If the user can select zero, one or more of the items in the list to filter the results you could do this:
    csharp Code:
    1. SqlConnection connection = new SqlConnection("connection string here");
    2. SqlCommand command = new SqlCommand();
    3. StringBuilder query = new StringBuilder("SELECT * FROM MyTable");
    4.  
    5. switch (this.listBox1.SelectedItems.Count)
    6. {
    7.     case 0:
    8.         break;
    9.     case 1:
    10.         query.Append(" WHERE MyColumn = @MyColumn");
    11.         command.Parameters.AddWithValue("@MyColumn", this.listBox1.SelectedItem);
    12.         break;
    13.     default:
    14.         query.Append(" WHERE MyColumn IN (");
    15.  
    16.         string paramName;
    17.  
    18.         for (int index = 0; index < this.listBox1.SelectedItems.Count; index++)
    19.         {
    20.             paramName = "@MyColumn" + index.ToString();
    21.  
    22.             if (index > 0)
    23.             {
    24.                 query.Append(", ");
    25.             }
    26.  
    27.             query.Append(paramName);
    28.             command.Parameters.AddWithValue(paramName, this.listBox1.SelectedItems[index]);
    29.  
    30.         }
    31.  
    32.         query.Append(")");
    33.         break;
    34. }
    35.  
    36. command.CommandText = query.ToString();
    37. command.Connection = connection;

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width