March 6, 2008

Reading The Number Of Rows In A Table Search

const string NUM_XXX = 
"SELECT COUNT(*) AS numXXXs"
"FROM ... 
"WHERE ...

using (databaseConnection = new SqlConnection(XXXConnectionString))
{
    databaseConnection.Open();
    using (SqlCommand command = new SqlCommand())
    {
        command.Connection = databaseConnection;
        command.CommandText = NUM_XXX;
        command.Parameters.AddWithValue("@Id", id);

        SqlDataReader reader = command.ExecuteReader();
        if (reader != null)
        {
            if (reader.HasRows && reader.Read())
            {
                numXXXs = reader.GetInt32(0);
            }
            reader.Close();
        }

    }
}

No comments: