Home > Articles > ADO.NET >

 How to use ExecuteScalar() method

Ganeshji
Posted by under ADO.NET category on for Beginner level | Points: 250 | Views : 55021 red flag
Rating: 3 out of 5
3 vote(s)
This article is describing the use of ExecuteScalar() method.

Introduction


We can use ExecuteScalar() method, if we have to retrieve a single value from a database. It executes the query and returns the first column of the first row in the result set returned by the query. Additional rows and columns are simply discarded. It returns a maximum of 2033 characters. It is better to get the result of MAX,MIN,COUNT, etc using ExecuteScalar() method.

Benefit


1. ExecuteScalar() requires the less code than using ExecuteReader().
2. ExecuteScalar() immediately returns the actual value. Hence, in case of retrieving single value from a database, it is fast and efficient.


INSERT










The following figure shows the records inserted using cmd.ExecuteScalar() method.






MAX








MIN





COUNT





Returns an object type


ExecuteScalar() method returns an object type.



So when i m trying to initialize the result of cmd.ExecuteScalar() method in an integer variable, it is giving the below given error.






Conclusion


Happy Reading!

Reference


http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar.aspx


Page copy protected against web site content infringement by Copyscape
About the Author
Ganeshji
Full Name: Zinnia Sarkar
Member Level:
Member Status: Member
Member Since: 7/24/2010 12:50:40 PM
Country: India
Regards, Ganeshji

Login to vote for this post.


Comments or Responses

Posted by: Seenuvasan on: 6/10/2011 | Points: 25
nice article ganeshji
Posted by: Ganeshji on: 6/10/2011 | Points: 25
Thnx Seenuvasan!
Posted by: Akiii on: 8/16/2011 | Points: 25
good article zinnia...

Thanks and Regards
Akiii
Posted by: Ganeshji on: 8/17/2011 | Points: 25
Thnx Akii!
Posted by: Ksuresh on: 12/26/2011 | Points: 25
Good Article and Thanx for in solving my problem....
Posted by: Ganeshji on: 12/26/2011 | Points: 25
Thnx Ksuresh! Keep reading!
Posted by: Shameer.Ali87 on: 6/6/2012 | Points: 25
nice article Ganeshji....
Posted by: Sangeetha Mani on: 3/4/2013 | Points: 25
hi ,

thanks for posting this article.. but i have confused .. actually execute scalar method for aggregate function. then why should you using insert command .. ?

Login to post response

Comment using Facebook(Author doesn't get notification)