When to use ExecuteScalar??? RRS feed

  • Question

  • Can anyone send me some links on ExecuteScalar or tell me when is it good to use this method.....I know it returns a single element but i dont understand the context of how it just retrieves a single element???

    Wednesday, August 23, 2006 2:27 PM


  • Well I guess say if you executed a query which returns 1 row and 1 column of data, or you have several columns but only want 1 column of the first row of data (saying this would also be bad practice), then it would be something you would use it for.


    So for example I could have a query (simple query nothing too complicated) which would return me some calculation:


    SELECT 4 + 3 AS 'Results'


    would return me 7 in the column name "Results" - this would be one way of using the ExecuteScaler method I guess.

    ExecuteScaler is used for these types of situations/problems I guess, as with the ExecuteNonQuery() is totally different and that is used for SELECT, INSERT, DELETE or UPDATE commands which only returns back the number of rows effected by the command.

    Wednesday, August 23, 2006 2:46 PM

    Assuming the error is generated at the assigment statement for your count value you probably need to convert it to an integer:


    Dim SumVal As Int32 = 0



    SumVal = Convert.ToInt32(cmd.ExecuteScalar())

    Tuesday, April 17, 2007 3:54 PM
  • Always use ExecuteNonQuery except: when you have a set of records - use ExecuteReader and when you have a single output value that cannot be defined as a parameter - use ExecuteScalar. Hope this helped to clarify something. Enjoy Smile
    Thursday, July 17, 2008 7:55 AM

All replies