Generally we confused when to use Dataset and when to use DataTable. In this article we discuss about Dataset, DataTable and when to use. Dataset is the collection of DataTables, which means it is a container of DataTables whereas DataTable is single element.
It is totally based on our requirement to select between Dataset andDataTable. If you are calling SQL stored procedure which returns multiple tables of data as shown below.
SET ANSI_NULLSON
GO
SET QUOTED_IDENTIFIERON
GO
CREATE PROCEDURE [dbo].[s_GetData]
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
SELECT * FROM emp
SELECT * FROM empSal
SELECT * FROM empDetails
END
GO
As shown above, the stored procedure is returning the data from three tables emp, empSal, empDetails. You can call this stored procedure as shown below.
using System;
using System.Data;
using System.Data.SqlClient;
public partial class_Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
try
{
SqlConnection con = new SqlConnection("Data Source=Home\\MSSQLSERVER2008;Initial Catalog=test;User ID=sa;Password=abc@123");
DataSet ds = newDataSet();
SqlDataAdapter dad = new SqlDataAdapter("s_GetData", con);
dad.Fill(ds);
DataTable dt1 = ds.Tables["emp"];
DataTable dt2 = ds.Tables["empSal"];
DataTable dt3 = ds.Tables["empDetails"];
}
catch (Exception ex)
{ }
}
}
As shown above, we are calling the stored procedure and storing the three table’s data in dataset. We can get each table data from dataset by using ds.Tables[“tablename”] or ds.Tables[tabeIndex].
If your store procedure is returning the single table data, store that data in DataTable object instead of DataSet object because DataTable object is lighter than DataSet object.