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 database As String, _ ByVal commandText As String, _ ByVal ParamArray parameters As SqlParameter() _ ) As Object [C#] public static object ExecuteScalar( string database, string commandText, params SqlParameter[] parameters ); [C++] public: static Object* ExecuteScalar( String* database, String* commandText, SqlParameter* parameters __gc[] ); [JScript] public static function ExecuteScalar( String database, String commandText, SqlParameter[] parameters ): 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#]DatabaseUtility.Connection = new SqlConnection("Server=127.0.0.1;Database=Northwind;Uid=sa;Pwd=;"); string customerName = DatabaseUtility.ExecuteScalar( "Northwind", "SELECT CustomerName FROM Customers WHERE CustomerID = '@CustomerID'", new SqlParameter("@CustomerID", "ALFKI") );[Visual Basic]DatabaseUtility.Connection = New SqlConnection("Server=127.0.0.1;Database=Northwind;Uid=sa;Pwd=;") string customerName = DatabaseUtility.ExecuteScalar( _ "Northwind", _ "SELECT CustomerName FROM Customers WHERE CustomerID = '@CustomerID'", _ new SqlParameter("@CustomerID", "ALFKI") _ )
DatabaseUtility Class | Joel.Net Namespace | DatabaseUtility.ExecuteScalar Overload List