.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Gaurav Pal

Home >> Code Snippets >> ADO.NET >> Post New Resource Bookmark and Share   

 Subscribe to Code Snippets

ExecuteScalar to Retrieve a Single Item

Posted By:Shashi Ray       Posted Date: November 30, 2009    Points: 10    Category: ADO.NET    URL: http://www.dotnetspark.com  


ExecuteScalar to Retrieve a Single Item

The ExecuteScalar method is designed for queries that return only a single value. In the event of the query returning multiple columns and/or rows, ExecuteScalar returns only the first column of the first row.

The following code shows how to look up the product name for a specific product ID:

void GetProductNameExecuteScalar( int ProductID, out string ProductName )
  using( SqlConnection conn = new SqlConnection(
         "server=(local);Integrated Security=SSPI;database=northwind") )
    SqlCommand cmd = new SqlCommand("LookupProductNameScalar", conn );
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.Add("@ProductID", ProductID );
    ProductName = (string)cmd.ExecuteScalar();

To use ExecuteScalar to retrieve a single item

  1. Establish a SqlCommand object to call a stored procedure.
  2. Open the connection.
  3. Call the ExecuteScalar method. Notice that this method returns an object type. This contains the value of the first column retrieved and must be cast to the appropriate type.
  4. Close the connection.

The preceding code uses the following stored procedure:

CREATE PROCEDURE LookupProductNameScalar
@ProductID int
SELECT TOP 1 ProductName
FROM Products
WHERE ProductID = @ProductID


Shashi Ray


Further Readings:


No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More code samples in C#, ASP.Net, Vb.Net and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend