Results 1 to 4 of 4

Thread: Help with ExecuteScalar

  1. #1

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

    Help with ExecuteScalar

    hi guyz!!! can anybody please help me...CUrrently, i have this code below
    Code:
    string qryStr = "Select Max(id) from users";
    sqlCOmmand sqlCmd = new SqlCommand (qryStr, sqlConn);
    int max_number = (int)sqlCmd.ExecuteScalar ();
    sqlConn.Close ();
    return max_number;
    as you can see i dont have a way if '(int)sqlCmd.ExecuteScalar ();' really returns a value or should i say had retrieved a value from my users table. My question is, how will check if '(int)sqlCmd.ExecuteScalar ();' method had retrieve or has a value. THanks in advance!!

  2. #2
    Banned
    Join Date
    Nov 2005
    Posts
    2,367

    Re: Help with ExecuteScalar

    If the table exists and it's a valid field name, how can it not return a value? (btw, ID should be in [] as it's a reserved word).

    If you want to check if it has a value, use a simple if/then/else and return what you would preffer as a default. Or, in the transact statement, use:

    "Select isnull(Max([id]), 0) from users"

    Change the 0 to whatever default value you want to return.

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

    Re: Help with ExecuteScalar

    Code:
    object result = sqlCmd.ExecuteScalar();
    
    if (result is int)
    {
        // The query returned an integer value.
    }
    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

  4. #4

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

    Re: Help with ExecuteScalar

    If the table exists and it's a valid field name, how can it not return a value?
    users table and field name exist and they both have valid name, is just that i dont have any rows from my users tables


    Code:
    object result = sqlCmd.ExecuteScalar();
    
    if (result is int)
    {
        // The query returned an integer value.
    }
    Since I assigned the return value to result which is in type object how can i convert it to int type? i already tried the
    Code:
    int.parse(result)
    but it won't work.
    Last edited by daimous; Jul 31st, 2006 at 10:05 PM.

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