Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
ExecuteScalar Method

IDbCommand.ExecuteScalar Method

Executes the query, and returns the first column of the first row in the resultset returned by the query. Extra columns or rows are ignored.

[Visual Basic]
Function ExecuteScalar() As Object
object ExecuteScalar();
Object* ExecuteScalar();
function ExecuteScalar() : Object;

Return Value

The first column of the first row in the resultset.


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 an IDataReader.

A typical ExecuteScalar query can be formatted as in the following C# example:

CommandText = "select count(*) as NumberOfRegions from region";
Int32 count = (int) ExecuteScalar();


[Visual Basic, C#, C++] The following example creates an instance of the derived class, 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)
End Sub 'CreateMySqlCommand

public void CreateMySqlCommand(string myScalarQuery, SqlConnection myConnection) 
    SqlCommand myCommand = new SqlCommand(myScalarQuery, myConnection);

    void CreateMySqlCommand(String* myScalarQuery, SqlConnection* myConnection)
        SqlCommand* myCommand = new SqlCommand(myScalarQuery, myConnection);

[JScript] No example is available for JScript. To view a Visual Basic, C#, or C++ example, click the Language Filter button Language Filter in the upper-left corner of the page.


Platforms: Windows 98, Windows NT 4.0, Windows Millennium Edition, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003 family, .NET Compact Framework

See Also

IDbCommand Interface | IDbCommand Members | System.Data Namespace

© 2015 Microsoft