2012-07-28 6 views
0

나는 count (ProductQuantity)를리스트에 저장했다. 각 ProductID가 다른 개수 (ProductQuantity)를 갖기 때문에 Count (ProductQuanity)를 기준으로 ProductID를 검색하려고합니다.where count sql statement

For Each i In sumofpquantity() 

    Dim sq As String = "SELECT ProductID From OrderDetail Where COUNT(ProductQuantity)= " & i & "" 
     Dim cmd2 As SqlCommand = New SqlCommand(sq, connection12) 
     Dim reading As SqlDataReader = cmd2.ExecuteReader() 
     While reading.Read() 

      list.Add(reading.GetInt32(reading.GetOrdinal("ProductID"))) 

     End While 
     reading.Close() 
    Next i 

sumofpquantity()는 수 (ProductQuanity) 개수에 따라 제품 ID (ProductQuantity)

답변

0

그래서 당신이 원하는을 검색 할 수있는 올바른 SQL 문을 무엇

를 저장하는 방법이다 기록

Dim sq = "SELECT ProductID From OrderDetail Where ProductQuantity = " & i 

COUNT 집계 기능입니다 : 주어진 수량, 다음 단순히 COUNT 제거. 예를 들어 GROUP BY ProductID이 필요합니다. 이미 하나의 숫자 값인 것을 셀 수는 없습니다.

0

having 절을 사용하여 특정 발생 횟수의 제품을 검색 할 수 있습니다. 예를 들어,이 42의 판매와 함께 제품을 찾습니다

select ProductID 
from OrderDetail 
group by 
     ProductID 
having SUM(ProductQuantity) = 42 

는 데이터베이스에 수 (42)을 통과 매개 변수 사용을 고려하려면

Dim sq As String = _ 
    "select ProductID" & _ 
    "from OrderDetail" & _ 
    "group by" & _ 
    "  ProductID" & _ 
    "having SUM(ProductQuantity) = @cnt" 
Dim cmd2 As SqlCommand = New SqlCommand(sq, connection12) 
cmd2.Parameters.AddWithValue("@cnt", 42); 
... 
0

글쎄, paramaterized 쿼리를 사용하는 것이 좋습니다 이 같은 :이 쿼리와

Dim sq as String = "SELECT ProductID " & _ 
        "FROM OrderDetail " & _ 
        "WHERE ProductQuantity = @DesiredQuantity" 
Dim cmd2 as SqlCommand = New SqlCommand(sq, connection12) 
cmd2.Parameters.AddWithValue("@DesiredQuantity", i) 

, SQL은 ProductQuantity = @DesiredQuantity와 제품에 대한보고, @DesiredQuantity는 i 변수의 값이 할당됩니다. 매개 변수는 SQL 주입을 방지합니다.