Export (0) Print
Expand All

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
[C#]
object ExecuteScalar();
[C++]
Object* ExecuteScalar();
[JScript]
function ExecuteScalar() : Object;

Return Value

The first column of the first row in the resultset.

Remarks

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();

Example

[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)
    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++] 
public:
    void CreateMySqlCommand(String* myScalarQuery, SqlConnection* myConnection)
    {
        SqlCommand* myCommand = new SqlCommand(myScalarQuery, myConnection);
        myCommand->Connection->Open();
        myCommand->ExecuteScalar();
        myConnection->Close();
    }

[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.

Requirements

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

Show:
© 2014 Microsoft