2011-01-09 26 views
3

ここから、セッションから複数の値を取得しようとしていたときのASPXコードスニペットがあります。 「コンマの近くに不適切な構文」(スニペット内の行をマークし)::コンマ区切りの構文が正しくありません

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

私は何をしないのです、私はエラーを取得していますか?

+3

あなたの質問に対する回答を受け入れる必要があります。 – SLaks

+1

あなたは最高の答えを受け入れる必要があります: – Kuncevic

答えて

7

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) 
+1

あなたはかっこが必要ありません。 – SLaks

+0

はい、これらは元のコードでありましたので、ちょうど持ち越されました。今すぐ削除されました:) –

1

あなたのケースでは、複数の条件の代わりに、私はあなたのSQLクエリではなく、代わりにIN句を使用することをお勧めします。 .. + "" + ...私はあなたが将来的に同一または類似のエラーを持っているならば、あなたは、SQL Server上で直接クエリをチェックすることも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); 

を使用します。 New Queryウィンドウを開いてそこにSQLクエリをコピーして実行してください。その場合は次のようになります。

select id,name from plugins where id IN (1, 2, 3, 4) 
関連する問題