Joel.Net.DatabaseUtility.dll Class Library

DatabaseUtility.ExecuteScalar Method (SqlConnection, String, String, CommandType, SqlParameter[])

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, _ 
   ByVal commandType As CommandType, _ 
   ByVal ParamArray parameters As SqlParameter() _ 
) As Object
[C#]
public static object ExecuteScalar(
   SqlConnection connection,
   string database,
   string commandText,
   CommandType commandType,
   params SqlParameter[] parameters
);
[C++]
public: static Object* ExecuteScalar(
   SqlConnection* connection,
   String* database,
   String* commandText,
   CommandType commandType,
   SqlParameter* parameters __gc[]
);
[JScript]
public static function ExecuteScalar(
   SqlConnection connection,
   String database,
   String commandText,
   CommandType commandType,
   SqlParameter[] parameters
): Object;

Parameters

connection
Represents an open connection to a SQL Server database.
database
Changes the current database for an open System.Data.SqlClient.SqlConnection.
commandText
The text of the query.
commandType
Specifies how a command string is interpreted.
parameters
A list of type System.Data.SqlClient.SqlParameter that maps to the System.Data.SqlClient.SqlCommand.

Return Value

The first column of the first row in the result set, or a null reference if the result set is empty.

Remarks

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.

Example

[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 = @CustomerID", CommandType.Text, new SqlParameter("@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 = @CustomerID", CommandType.Text, new SqlParameter("@CustomerID", "ALFKI"))

See Also

DatabaseUtility Class | Joel.Net Namespace | DatabaseUtility.ExecuteScalar Overload List