2014-03-02 70 views
0

有沒有辦法做到這一點?我想檢索數據的每個計數在一個領域我想檢索一個字段中的每個計數特定數據

這裏是我的代碼..

Dim cmd1 As New SqlCommand("SELECT COUNT(support) AS support " & _ 
          "FROM Studz_Table WHERE support ='others'",conn) 
dim int1 as integer = cmd1.executescalar 

Dim cmd2 As New SqlCommand("SELECT COUNT(support) AS support " & _ 
          "FROM Studz_Table WHERE support ='myself'",conn) 
dim int2 as integer = cmd1.executescalar 
Dim cmd3 As New SqlCommand("SELECT COUNT(support) AS support " & _ 
          "FROM Studz_Table WHERE support ='parent'",conn) 
dim int3 as integer = cmd1.executescalar 

有沒有簡單的方法來做到這一點?

回答

1

您可以使用SUM和CASE的組合來檢索每種類型的計數。

Dim cmd As New SqlCommand("SELECT SUM(CASE WHEN support = 'others' THEN 1 ELSE 0 END) AS OthersCount, " & _ 
          "SUM(CASE WHEN support = 'myself' THEN 1 ELSE 0 END) AS MyselfCount, " & _ 
          "SUM(CASE WHEN support = 'parent' THEN 1 ELSE 0 END) AS ParentCount " & _ 
          "FROM Studz_Table WHERE support ='others'",conn) 

你需要使用ExecuteReader雖然不是ExecuteScalar訪問每一列:

SqlDataReader reader = command.ExecuteReader(); 
while (reader.Read()) 
{ 
    int int1 = reader[0]; 
    int int2 = reader[1]; 
    int int3 = reader[2]; 
} 
+0

yeah..that helps..tnx隊友.. – user3211476

+0

hmmm..another thing..can我們在SQL中使用循環在UPDATE? – user3211476

+1

@ user3211476:你的第二個問題看起來像一個不同的問題,請花時間先接受上述答案。然後問一個單獨的問題。謝謝。 – Neolisk

相關問題