In this article, I am going to discuss how to call a stored procedure and store the result in a DataSet using C# ADO.NET. Please read our previous article where we discussed how to call stored procedures using SqlCommand Object and using SqlDataReader.
Suppose, you are calling a stored procedure that returns a result set, then you can store that result set in a DataSet. Let us understand this with an example. We are going to use the following Employee table to understand this concept.
Please use the below SQL Script to Create and Populate the database EmployeeDB and table Employee with the required sample data.
Now, we will see how to call a stored procedure with input parameters using ADO.NET DataSet. Let us first create the SQL Server Stored Procedure inside the EmployeeDB database. So, please use the following SQL Script to create the stored procedure. The following stored procedure will return the list of employees based on Age and Department conditions. Here, Age and Dept are the input parameters, and those parameter values we need to pass while calling this stored procedure from our C#.NET Application.
The following example code is self-explained, so please go through the comment lines. In the below example, I am showing how to call SQL Server Stored Procedure with input parameters that return a result set and how we can store that result set in a DataSet or DataTable using ADO.NET and C#.
The following example code is self-explained, so please go through the comment lines. In the below example also, I am showing how to call the Stored Procedure which returns a result set and how we can store that result set in a DataSet using ADO.NET and C#.
Suppose you are writing a Helper class in your application that uses ADO.NET to interact with the database. And in your application, you are going to call Stored Procedures from many different places. Writing a generic Helper method that takes in an Array of SqlParameters can be used so that you do not have to re-write the same code of calling the Stored Procedure again and again which will save a lot of time in application development.
We are having a stored procedure called spGetEmployeesByAgeDept which returns the list of employees by Age and Department. Let us create another stored procedure that is going to return all the Employees. Please execute the below SQL Statement.
Now, let us see the process of creating a generic method that will execute the stored procedure with and without parameters and returns a DataSet. For a better understanding, please have a look at the following example. The following example code is self-explained, so please go through the comment lines.
In the next article, I am going to discuss the ADO.NET DataView Class in C# with Examples. Here, in this article, I try to explain ADO.NET DataSet Using a Stored Procedure with Examples. I hope you enjoy this ADO.NET DataSet Using Stored Procedure in C# with Examples article.