Export (0) Print
Expand All
0 out of 1 rated this helpful - Rate this topic

Obtaining a Single Value from a Database

You may need to return database information that is simply a single value rather than in the form of a table or data stream. For example, you may want to return the result of an aggregate function such as Count(*), Sum(Price), or Avg(Quantity). The Command object provides the capability to return single values using the ExecuteScalar method. The ExecuteScalar method returns as a scalar value the value of the first column of the first row of the result set.

The following code example returns the number of records in a table using the Count aggregate function.

Dim ordersCMD As SqlCommand = New SqlCommand("SELECT Count(*) FROM Orders", nwindConn)

Dim count As Int32 = CInt(ordersCMD.ExecuteScalar())
[C#]SqlCommand ordersCMD = new SqlCommand("SELECT Count(*) FROM Orders", nwindConn);

Int32 count = (Int32)ordersCMD.ExecuteScalar();

See Also

Using .NET Framework Data Providers to Access Data | OleDbCommand Class | OleDbConnection Class | OdbcCommand Class | OdbcConnection Class | SqlCommand Class | SqlConnection Class

Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft. All rights reserved.