如何将存储过程的多个结果存储到数据集中?

如何将StoredProcedure中的结果集合并到ASP.NET中的一个数据集中?

下面是我在asp.net中的代码

SqlDataAdapter adap = new System.Data.SqlClient.SqlDataAdapter("sp_Home_MainBanner_TopStory",con); adap.SelectCommand.CommandType = CommandType.StoredProcedure; adap.SelectCommand.Parameters.AddWithValue("@rows", 9); DataSet DS = new DataSet(); adap.Fill(DS, "Table1"); adap.Fill(DS, "Table2"); GridView1.DataSource = DS.Tables["Table2"]; GridView1.DataBind(); 

即使有两个适配器,我怎样才能将结果合并到一个数据集中?

DataSet包含表。 对于上面的示例,如果您有两个SqlDataAdapter,每个都调用一个存储过程并像上面一样存储它们。

 adapter1.Fill(DS, "Table1"); adapter2.Fill(DS, "Table2"); 

这将获取第一个查询的表结果,并将其作为Table1存储在DataSet DS中。 然后它将在同一个DataSet中存储另一个Table(Table2)。 要访问这些表,请使用以下代码:

 DS.Tables["Table1"] //Or Table2, or whatever you name it during your Fill. 

您已经拥有了正确的流程,您只需要查看DataSet的工作方式并决定如何调用您的信息。

如果要将结果合并到一个DataTable中,则需要遍历表并组合信息。

 ex: DataTable combinedTable = new DataTable(); //Create columns foreach (DataRow row in DS.Tables["Table1"].Rows) { //Create rows? Copy information over? Whatever you want to do. } 

MS SQL我们创建一个过程,如:

 [ create proc procedureName as begin select * from student select * from test select * from admin select * from result end ] 

C# ,我们编写以下代码以在DataSet检索这些值

 { SqlConnection sqlConn = new SqlConnection("data source=(local);initial catalog=bj001;user id=SA;password=bj"); SqlCommand sqlCmd = new SqlCommand("procedureName", sqlConn); sqlCmd.CommandType = CommandType.StoredProcedure; sqlConn.Open(); SqlDataAdapter sda = new SqlDataAdapter(sqlCmd); DataSet ds = new DataSet(); sda.Fill(ds); sqlconn.Close(); // Retrieving total stored tables from a common DataSet. DataTable dt1 = ds.Tables[0]; DataTable dt2 = ds.Tables[1]; DataTable dt3 = ds.Tables[2]; DataTable dt4 = ds.Tables[3]; // To display all rows of a table, we use foreach loop for each DataTable. foreach (DataRow dr in dt1.Rows) { Console.WriteLine("Student Name: "+dr[sName]); } } 

试着用这个:

 adapter1.Fill(DS, "Table1, Table2"); 

这在这里有效……