Skip to content

Latest commit

 

History

History
32 lines (24 loc) · 1.57 KB

File metadata and controls

32 lines (24 loc) · 1.57 KB
title Obtaining a single value from a database
description Learn how to return a single value in ADO.NET. This example code returns the identity column value for an inserted record.
author David-Engel
ms.author davidengel
ms.reviewer v-chmalh
ms.date 11/25/2020
ms.service sql
ms.subservice connectivity
ms.topic how-to
dev_langs
csharp

Obtaining a single value from a database

[!INCLUDE dotnet-all]

[!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.

Example

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]

See also