帮我处理以下sql查询

时间:2010-06-13 04:54:18

标签: sql mysql

有人可以更正我的以下查询,我是软件开发领域的新手, 我是一个逗号分隔形式的字符串生成器对象到我的查询,但它没有产生所需的结果qyery如下所示 string cmd =“SELECT * FROM [placement_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..

1 个答案:

答案 0 :(得分:1)

你的问题在于:

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

您最终会得到一个类似的查询:

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

如果branch_id列是一个整数,则不应该引用它,并且应该稍微不同地插入逗号以避免使用逗号,例如:

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 + ")";

这可以通过在添加每个项目后将初始分隔符设置为空字符串然后再设置为逗号来实现。因此,当添加A,B和C时,您将获得“A”,“A,B”和“A,B,C”。我还删除了对整数的错误引用。

您可能还需要注意没有选择任何项目的情况,否则您将最终得到:

... AND branch_id IN ()