SQL Count() function. and setting variables
public void GetUsersDetails(Guid i)
{
StringBuilder sb = new StringBuilder();
sb.Append("DECLARE @NumberOfThreadsByOneUser smallin开发者_JAVA百科t;");
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 u.UsersID=@UserID)");
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;
}
}
I wrote an SQL statement and what I want to get is the number of threads submitted by a user. So I declared a smallint variable. But i am not sure about the syntax of my sql statement. I want to read from the result. The QA int property should receive that count number..
Use select
instead of set
to assign a variable based on a query:
sb.Append(" SELECT @NumberOfThreadsByOneUser = (SELECT COUNT(t.threadID)");
To use an output variable, do not declare it in SQL, but pass it:
cmd.Parameters.Add("@NumberOfThreadsByOneUser").ParameterDirection =
ParameterDirection.InputOutput;
Then after the command executes, you can retrieve it:
var result = cmd.Parameters("@NumberOfThreadsByOneUser").Value
Alternatively, using the reader approach, don't declare the variable in SQL and don't pass it as a parameter.
sb.Append(" SELECT COUNT(t.threadID) as ThreadCount");
....
sb.Append(" WHERE u.UsersID=@UserID"); // <-- no closing )
And read it like:
var QA = (int) cmd.ExecuteScalar();
Or:
var read = cmd.ExecuteReader();
read.Read(); // <-- Gotta move to the first row
var QA = (int) read["ThreadCount"]; // <-- or whatever your column alias is
精彩评论