SqlCeCommand.ExecuteScalar Method

Note: This namespace, class, or member is supported only in version 1.1 of the .NET Framework.

Executes the query and returns the first column of the first row in the result set that is 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.

Implements

IDbCommand.ExecuteScalar

Exceptions

Exception Type Condition
InvalidOperationException Cannot execute a command within a transaction context that differs from the context in which the connection was originally enlisted.

Remarks

Use the ExecuteScalar method to retrieve a single value (such as an aggregate value) from a data source. This requires less code than using the ExecuteReader method, and then performing the operations necessary to generate the single value by using the data returned by a SqlCeDataReader.

Example

[Visual Basic, C#] The following example creates a SqlCeCommand and then executes it using ExecuteScalar. The example is passed a string that is an SQL statement, which returns an aggregate result, and a string for connecting to the data source.

  [Visual Basic] 
Public Sub CreateMySqlCeCommand(ByVal myScalarQuery As String, ByVal myConnection As SqlCeConnection)
    Dim myCommand As New SqlCeCommand(myScalarQuery, myConnection)
    myCommand.Connection.Open()
    myCommand.ExecuteScalar()
    myConnection.Close()
End Sub

[C#] 
public void CreateMySqlCeCommand(string myScalarQuery, SqlCeConnection myConnection) {
    SqlCeCommand myCommand = new SqlCeCommand(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 Language Filter in the upper-left corner of the page.

Requirements

Platforms: .NET Compact Framework

.NET Framework Security:

See Also

SqlCeCommand Class | SqlCeCommand Members | System.Data.SqlServerCe Namespace

Syntax based on .NET Framework version 1.1.
Documentation version 1.1.1.

Send comments on this topic.

© Microsoft Corporation. All rights reserved.