System.Data.SqlClient.SqlCommand.ExecuteScalar Method

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

Syntax

public override object ExecuteScalar ()

Returns

The first column of the first row in the result set, or a null reference (Nothing in Visual Basic) if the result set is empty. Returns a maximum of 2033 characters.

Remarks

Use the SqlCommand.ExecuteScalar method to retrieve a single value (for example, an aggregate value) from a database. This requires less code than using the SqlCommand.ExecuteReader method, and then performing the operations that you need to generate the single value using the data returned by a System.Data.SqlClient.SqlDataReader.

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

Example

 cmd.CommandText = "SELECT COUNT(*) FROM dbo.region";
 Int32 count = (Int32) cmd.ExecuteScalar();

Requirements

Namespace: System.Data.SqlClient
Assembly: System.Data (in System.Data.dll)
Assembly Versions: 1.0.5000.0, 2.0.0.0