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] Shared OverloadsPublic Function ExecuteScalar( _ ByVal connection As SqlConnection, _ ByVal database As String, _ ByVal commandText As String _ ) As Object [C#] public static object ExecuteScalar( SqlConnection connection, string database, string commandText ); [C++] public: static Object* ExecuteScalar( SqlConnection* connection, String* database, String* commandText ); [JScript] public static function ExecuteScalar( SqlConnection connection, String database, String commandText ): Object;
The first column of the first row in the result set, or a null reference if the result set is empty.
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.
[C#, Visual Basic] 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.
[C#]SqlConnection connection = new SqlConnection("Server=127.0.0.1;Database=Northwind;Uid=sa;Pwd=;"); string customerName = DatabaseUtility.ExecuteScalar(connection, "Northwind", "SELECT CustomerName FROM Customers WHERE CustomerID = 'ALFKI'");[Visual Basic]Dim connection As New SqlConnection("Server=127.0.0.1;Database=Northwind;Uid=sa;Pwd=;") Dim customerName As String = DatabaseUtility.ExecuteScalar(connection, "Northwind", "SELECT CustomerName FROM Customers WHERE CustomerID = 'ALFKI'")
DatabaseUtility Class | Joel.Net Namespace | DatabaseUtility.ExecuteScalar Overload List