title | description | author | ms.author | ms.reviewer | ms.date | ms.service | ms.subservice | ms.topic | dev_langs | |
---|---|---|---|---|---|---|---|---|---|---|
Obtaining a single value from a database |
Learn how to return a single value in ADO.NET. This example code returns the identity column value for an inserted record. |
David-Engel |
davidengel |
v-chmalh |
11/25/2020 |
sql |
connectivity |
conceptual |
|
[!INCLUDEappliesto-netfx-netcore-netst-md]
[!INCLUDEDriver_ADONET_Download]
You may need to return database information that is simply a single value rather than in the form of a table or data stream. For example, you may want to return the result of an aggregate function such as COUNT(*), SUM(Price), or AVG(Quantity). The Command object provides the capability to return single values using the ExecuteScalar method. The ExecuteScalar method returns, as a scalar value, the value of the first column of the first row of the result set.
The following code example inserts a new value in the database using a xref:Microsoft.Data.SqlClient.SqlCommand. The xref:Microsoft.Data.SqlClient.SqlCommand.ExecuteScalar%2A method is used to return the identity column value for the inserted record.
[!code-csharpDataWorks SqlCommand.ExecuteScalar#1]