Use the ExecuteScalar method to retrieve a single value (for example, an aggregate value) from a database. This requires less code than using the ExecuteReader method, and then performing the operations necessary to generate the single value using the data returned by a SqlDataReader.
A typical ExecuteScalar query can be formatted as in the following C# example:
CommandText = "select count(*) as NumberOfRegions from region";
Int count = (int) ExecuteScalar();
Example
[Visual Basic, C#] The following example creates a SqlCommand and then executes it using ExecuteScalar. The example is passed a string that is a Transact-SQL statement that returns an aggregate result, and a string to use to connect to the data source.
[Visual Basic]
Public Sub CreateMySqlCommand(myScalarQuery As String, myConnection As SqlConnection)
Dim myCommand As New SqlCommand(myScalarQuery, myConnection)
myCommand.Connection.Open()
myCommand.ExecuteScalar()
myConnection.Close()
End Sub 'CreateMySqlCommand
[C#]
public void CreateMySqlCommand(string myScalarQuery, SqlConnection myConnection)
{
SqlCommand myCommand = new SqlCommand(myScalarQuery, myConnection);
myCommand.Connection.Open();
myCommand.ExecuteScalar();
myConnection.Close();
}
[C++, JScript] No example is available for C++ or JScript. To view a Visual Basic or C# example, click the Language Filter button in the upper-left corner of the page.