Results 1 to 2 of 2

Thread: Help with my query string

  1. #1

    Thread Starter
    Fanatic Member daimous's Avatar
    Join Date
    Aug 2005
    Posts
    657

    Help with my query string

    hi guys! i have a code below that query something from my database
    Code:
    string SqlConnStr = Properties.Settings.Default.MyConnString;
    sqlConn = new SqlConnection(SqlConnStr);
    sqlConn.Open();
    string qryStr = "Select Max(number) from docs_ref";
    SqlCommand SqlCmd = new SqlCommand(qryStr, sqlConn);
    object result = SqlCmd.ExecuteScalar();
    SqlCmd.Connection.Close();
    sqlConn.Close();
    but how can I check if it does return any value or not and if it does how can i retrieve the value? thanks.
    Last edited by daimous; Sep 17th, 2006 at 09:56 PM.

  2. #2
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: Help with my query string

    Code:
    object result = SqlCmd.ExecuteScalar();
    The 'result' variable contains the value returned by the query. I'm not 100% sure but I would guess that if the 'number' column contains no values then 'result' would contain DBNull.Value. I am sure that if the 'number' column does contain values then 'result' will contain the largest of them and its type will correspond to the type of the column. If the column contains integers:
    Code:
    object result = SqlCmd.ExecuteScalar();
    
    if (result is int)
    {
        // Cast the result as an integer.
        int maxNumber = (int)result;
    
        // Use maxNumber here.
    }
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width