【问题标题】:Incorrect syntax near comma逗号附近的语法不正确
【发布时间】:2011-01-09 16:14:01
【问题描述】:

这是我尝试从会话中获取多个值时的 ASPX 代码 sn-p。我收到一个错误:“逗号附近的语法不正确”(在 sn-p 中标记了该行):

SqlCommand cmd1 = new SqlCommand("select plugin_id from profiles_plugins where profile_id=" + Convert.ToInt32(Session["cod"]), con);
        SqlDataReader dr1 = cmd1.ExecuteReader();
        var yourlist =new List<Int32>();
        if (dr1.HasRows)
        {
            while (dr1.Read())
            {
                yourlist.Add(Convert.ToInt32(dr1[0]));
            }
        }

        //String str1 = String.Join(", ", yourlist.Select(o => o.ToString()).ToArray());
            dr1.Close();
        cmd1.Dispose();
        Array k= yourlist.ToArray();
        Int32 a =Convert.ToInt32( k.GetValue(0));
        Int32 b =Convert.ToInt32( k.GetValue(1));
        Int32 c =Convert.ToInt32( k.GetValue(2));
        Int32 d =Convert.ToInt32( k.GetValue(3));
        SqlCommand cmd2 = new SqlCommand("select id,name from plugins where id =(" + a + " or " + b + " or " + c + " or " + d +  ")" , con); /// Error here?
        SqlDataReader dr2 = cmd2.ExecuteReader(); ///Error here?
        if (dr2.HasRows)
        {
            while (dr2.Read())
            {
                ListBox2.DataSource = dr2;
                ListBox2.DataBind();
            }
        }
        dr2.Close();
        cmd2.Dispose();
con.Close();

我错过了什么?

【问题讨论】:

  • 你应该接受你的问题的答案。
  • 你应该接受最好的答案:)

标签: asp.net sql


【解决方案1】:

SQL 查询错误。将其更改为:

    SqlCommand cmd2 = new SqlCommand("select id,name from plugins   
where id in(" + a + " , " + b + " , " + c + " , " + d +  ")" , con);

【讨论】:

    【解决方案2】:

    这一行出错。试试这个

    SqlCommand cmd2 = new SqlCommand("select id,name from plugins where id =" + a + "or id =" + b + " or id =" + c + " or id =" + d +  "" , con)
    

    【讨论】:

    • 是的,因为这些都是原始代码,所以继续进行。现已删除:)
    【解决方案3】:

    在您的情况下,而不是多个条件,或者我建议在您的 SQL 查询中使用 IN 子句,而不是 ... + "" + ... 我会使用 String.Format

    SqlCommand cmd2 = new SqlCommand(String.Format("select id,name from plugins where id IN ({0}, {1}, {2}, {3}", a, b, c, d,) con);
    

    此外,如果您将来遇到相同或类似的错误,您可以直接在 SQL Server 上检查您的查询。只需打开 New Query 窗口并在那里复制您的 SQL 查询,然后运行它。在这种情况下,它会是这样的:

    select id,name from plugins where id IN (1, 2, 3, 4)
    

    【讨论】:

      猜你喜欢
      • 2016-02-07
      • 2015-12-12
      • 2013-12-16
      • 1970-01-01
      • 2018-08-14
      • 2011-03-11
      • 2014-02-16
      • 2017-01-11
      • 2020-02-06
      相关资源
      最近更新 更多