tags:

views:

53

answers:

2

could somebody correct my following query, i am novice to software development realm, i am to a string builder object in comma separated form to my query but it's not producing desired result qyery is as follows and string cmd = "SELECT * FROM [placed_student] WHERE passout_year=@passout AND company_id=@companyId AND course_id=@courseId AND branch_id IN('" + sb + "')";

  StringBuilder sb = new
  StringBuilder();
              foreach (ListItem li in branch.Items)
              {

                  if (li.Selected == true)
                  {
                      sb.Append(Convert.ToInt32(li.Value)
  +", ");
                  }
              }
 li is integer value of my check box list which are getting generated may be differne at different time ...please also suggest me some good source to learn sql..
A: 

friends, you can first format the text.

parsifal
+1  A: 

Your problem lies here:

AND branch_id IN('" + sb + "')"

You'll end up with a query like:

... AND branch_id IN('1,2,3,')

If the branch_id column is an integer, you should not be quoting it, and you should insert the commas slightly differently to avoid a trailing one, such as with:

StringBuilder sb = new StringBuilder();
String sep = "";
foreach (ListItem li in branch.Items) {
    if (li.Selected == true) {
        sb.Append (sep + Convert.ToInt32(li.Value));
        sep = ",";
    }
}
String cmd = "SELECT * FROM [placed_student] " +
      "WHERE passout_year = @passout " +
      "AND company_id = @companyId " +
      "AND course_id = @courseId " +
      "AND branch_id IN (" + sb + ")";

This works by setting the initial separator to an empty string then to a comma after adding each item. So, when adding A, B and C, you'll get "A", "A,B" and "A,B,C'. I also removes the erroneous quoting on integers.

You'll also probably need to catch the case where none of your items are selected since otherwise you'll end up with:

... AND branch_id IN ()
paxdiablo
yes it worked ...thanks sir/ madam .........thanks a lot...
NoviceToDotNet