ExecuteScalar Method

SqlCommand.ExecuteScalar Method

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

[Visual Basic]
Public Overridable Function ExecuteScalar() As Object Implements _
   IDbCommand.ExecuteScalar
[C#]
public virtual object ExecuteScalar();
[C++]
public: virtual Object* ExecuteScalar();
[JScript]
public function ExecuteScalar() : Object;

Return Value

The first column of the first row in the result set, or a null reference if the result set is empty.

Implements

IDbCommand.ExecuteScalar

Exceptions

Exception Type Condition
SqlException An exception occurred while executing the command against a locked row. This exception is not generated when using Microsoft .NET Framework version 1.0.

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 a SqlDataReader.

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

cmd.CommandText = "select count(*) from region";
Int32 count = (int32) cmd.ExecuteScalar();

Example

[Visual Basic, C#, 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++] 
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

SqlCommand Class | SqlCommand Members | System.Data.SqlClient Namespace

Show:
© 2016 Microsoft