Share via


SqlCeCommand.ExecuteScalar Method

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.

Namespace: System.Data.SqlServerCe
Assembly: System.Data.SqlServerCe (in system.data.sqlserverce.dll)

Syntax

'Declaration
Public Overrides Function ExecuteScalar As Object
public override Object ExecuteScalar ()
public:
virtual Object^ ExecuteScalar () override
public Object ExecuteScalar ()
public override function ExecuteScalar () : Object

Return Value

The first column of the first row in the result set.

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

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.

Dim cmd As New SqlCeCommand("SELECT col1 FROM myTable", conn)
cmd.Connection.Open()
Dim value As Object = cmd.ExecuteScalar()
conn.Close()
SqlCeCommand cmd = new SqlCeCommand("SELECT col1 FROM myTable", conn);
cmd.Connection.Open();
object value = cmd.ExecuteScalar();
conn.Close();

Thread Safety

Any public static (Shared in Microsoft Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Platforms

Development Platforms

Windows Vista, Windows Mobile 5.0, Windows XP Professional with Service Pack 2 (SP2), Windows Server 2003, Windows Mobile 2003 for Pocket PC, Windows CE 5.0
Version Information
.NET Framework and NET Compact Framework
Supported in 3.5
.NET Framework
Supported in 3.0
.NET Compact Framework and .Net Framework
Supported in 2.0

See Also

Reference

SqlCeCommand Class
SqlCeCommand Members
System.Data.SqlServerCe Namespace