Incorrect comma syntax

Here is an ASPX code snippet when I tried to get multiple values ​​from a session. I get the error message: "Incorrect syntax near the comma" (the line in the fragment is marked):

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();

What am I missing?

+3
source share
3 answers

SQL Query is wrong. Change it to:

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

Error in this line. try it

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

IN SQL-, . .. + "" + ... 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. " " SQL- . - :

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

Source: https://habr.com/ru/post/1784388/


All Articles