2011-07-02 78 views
0
public void GetUsersDetails(Guid i) 
{ 
    StringBuilder sb = new StringBuilder(); 
    sb.Append("DECLARE @NumberOfThreadsByOneUser smallint;"); 
    sb.Append(" SET=(SELECT COUNT(t.threadID)"); 
    sb.Append(" FROM Threads AS t"); 
    sb.Append(" INNER JOIN Users AS u ON u.UsersID=t.UsersID"); 
    sb.Append(" WHERE [email protected])"); 

    string myConnectionString = AllQuestionsPresented.connectionString; 
    using (SqlConnection conn = new SqlConnection()) 
    { 
     SqlCommand cmd = new SqlCommand(sb.ToString(), conn); 
     cmd.Parameters.Add("UserID", SqlDbType.UniqueIdentifier).Value = i; 
     SqlDataReader dr = cmd.ExecuteReader(); 


dr.Read(); 
    QA = (Int32.TryParse(dr["NumberOfThreadsByOneUser"].ToString(), out result3)) ? int.Parse(dr["Replies"].ToString()) : 0; 
    } 
} 

我寫了一條SQL語句,我想得到的是用戶提交的線程數。所以我宣佈了一個smallint變量。但我不確定我的sql語句的語法。我想從結果中讀取。質量保證INT屬性應該收到計數..SQL Count()函數。並設置變量

回答

4

使用select而不是set分配基於查詢的變量:

sb.Append(" SELECT @NumberOfThreadsByOneUser = (SELECT COUNT(t.threadID)"); 

要使用的輸出變量,不要在SQL聲明,但通過它:

cmd.Parameters.Add("@NumberOfThreadsByOneUser").ParameterDirection = 
    ParameterDirection.InputOutput; 

然後執行此命令後,你可以找回:

var result = cmd.Parameters("@NumberOfThreadsByOneUser").Value 

或者,使用reader方法,不要在SQL中聲明變量,也不要將它作爲參數傳遞。

sb.Append(" SELECT COUNT(t.threadID) as ThreadCount"); 
.... 
sb.Append(" WHERE [email protected]"); // <-- no closing) 

讀它喜歡:

var QA = (int) cmd.ExecuteScalar(); 

或者:

var read = cmd.ExecuteReader(); 
read.Read(); // <-- Gotta move to the first row 
var QA = (int) read["ThreadCount"]; // <-- or whatever your column alias is