Obtaining a Single Value from a Database
This page is specific to:.NET Framework Version:1.12.03.03.54.0
.NET Framework Developer's Guide
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

© 2009 Microsoft Corporation. All rights reserved.   Terms of Use | Trademarks | Privacy Statement
Page view tracker
Rate the Lightweight library
x
Lightweight builds on ScriptFree (loband) by adding features you've requested: a SearchBox and default code language selection.
Do you like the SearchBox?
Do you like the tabbed code blocks?
How useful is this topic?
Tell us more.
Thanks
x
You're helping to improve MSDN Online.
Feedback
Switch View
Classic
Lightweight Beta
ScriptFree
Switch View