A Comprehensive Guide to Returning Data from SQL Stored Procedures to DataSet in C# .NET

Dec 03, 2025 · Programming · 8 views · 7.8

Keywords: C# | .NET | DataSet | Stored Procedure | SqlDataAdapter

Abstract: This article explains how to retrieve data from a SQL stored procedure and load it into a DataSet in C# .NET, with a focus on using SqlDataAdapter for efficient data handling. It includes code examples, method steps, and considerations to help developers achieve data integration.

Introduction

In C# .NET applications, integrating data from SQL Server stored procedures into DataSets is a common requirement for data manipulation and display. This article provides a step-by-step guide on how to achieve this, focusing on the use of SqlDataAdapter to fill a DataSet with the results returned by a stored procedure.

Method Overview

The primary method involves executing the stored procedure using SqlCommand with parameters, and then using SqlDataAdapter to retrieve the data and populate a DataSet. This approach ensures efficient data handling and prevents SQL injection by parameterizing queries.

Code Implementation

Here is a sample C# code based on the best answer:

DataSet ds = new DataSet("TimeRanges");
using(SqlConnection conn = new SqlConnection("ConnectionString"))
{               
    SqlCommand sqlComm = new SqlCommand("Procedure1", conn);               
    sqlComm.Parameters.AddWithValue("@Start", StartTime);
    sqlComm.Parameters.AddWithValue("@Finish", FinishTime);
    sqlComm.Parameters.AddWithValue("@TimeRange", TimeRange);
    sqlComm.CommandType = CommandType.StoredProcedure;
    SqlDataAdapter da = new SqlDataAdapter();
    da.SelectCommand = sqlComm;
    da.Fill(ds);
}

Explanation of the code:

Discussion and Considerations

While this method is effective, it is important to ensure that the stored procedure returns a result set that can be mapped to the DataSet. In the provided stored procedure, a common table expression (CTE) is used to generate time ranges and join with another table to count peaks. The result is automatically returned as a table that SqlDataAdapter can handle.

Additional points to consider include error handling, such as wrapping the code in try-catch blocks, and optimizing the stored procedure for performance if dealing with large datasets.

Conclusion

By following this approach, developers can seamlessly integrate SQL stored procedure data into C# .NET DataSets, enabling flexible data operations within the application. This method leverages the strengths of ADO.NET for database interactions.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.