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