DB2 Version 10.1 for Linux, UNIX, and Windows

DB2Command.ExecuteScalar Method

Executes the query, and returns the first column of the first row in the resultset returned by the query. Extra columns or rows are ignored.

Namespace:
IBM®.Data.DB2®
Assembly:
IBM.Data.DB2 (in IBM.Data.DB2.dll)

Syntax

[Visual Basic]
NotOverridable Public Function ExecuteScalar() As Object
[C#]
public object ExecuteScalar();
[C++]
public: __sealed Object* ExecuteScalar();
[JScript]
public function ExecuteScalar() : Object;

Return value

The first column of the first row in the resultset.

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 from the data returned by a   DB2DataReader .

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

CommandText = "select count(*) as NumberOfEmployee from EMPLOYEE";
Int count = (int) ExecuteScalar();

Example

[Visual Basic, C#] The following example creates a DB2Command and then executes it using ExecuteScalar. The example is passed a string that is an SQL statement that returns an aggregate result, and a string to use to connect to the database.

[Visual Basic]
Public Sub CreateMyDB2Command(myScalarQuery As String, 
    myConnection As DB2Connection)
    Dim myCommand As New DB2Command(myScalarQuery, myConnection)
    myCommand.Connection.Open()
    Dim qryValue As object = myCommand.ExecuteScalar()
    myConnection.Close()
End Sub 'CreateMyDB2Command

[C#]
public void CreateMyDB2Command(string myScalarQuery, DB2Connection myConnection)
 {
    DB2Command myCommand = new DB2Command(myScalarQuery, myConnection);
    myCommand.Connection.Open();
    object qryValue = myCommand.ExecuteScalar();
    myConnection.Close();
 }