好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

c# – 从sql server存储过程返回多个数据集

我需要通过Web Api返回基于调用运行5个不同查询的存储过程的Base64 XML输出.

存储过程没有编写(我需要编写)但有5个查询,其中数据是完全不同的表和列等…所以我想知道这是否可能?

我知道在Oracle中你可以返回多个游标,但是使用SQL Server,我可以返回到asp.net 4.5(mvc c#/ Ado.net)多个数据集或集合吗?这有什么例子吗?

只有一个查询的示例

-- Content Tab
SELECT -- vTC.[TemplateId]  
  t.Name as "Client Name and Document"  ,vTC.[SectionName] ,vTC.[ContentId] ,vTC.[ContentName]
  ,vTC.[ContentDescription],vTC.[ContentValue] ,CAL.ContentValue as "Spanish Content" , iif(S.IsClientSection = 1, 'Global Section','Template Section') as "Global or Template Section"
  ,DT.Title as DataType ,iif(vTC.IsRequired = 1, 'Yes', 'No') as "Required" ,vTC.[DisplayType] 
FROM [dbo].[vwTemplateContent] vTC
 left join dbo.Template t on vTC.TemplateId = t.TemplateId
  left join dbo.DataType DT on vTC.DataTypeId = dt.datatypeid
   left join dbo.Section S on S.SectionID = vTC.SectionID
   left join [dbo].[ContentAlternateLanguage] CAL on vTC.ContentId =    CAL.ContentID
  where vTC.templateid in (1) 
  order by DisplayOrder
如果要获得多个表,则必须在存储过程中编写多个select语句,如下所示:

CREATE PROCEDURE SPName
(
/*Declare your parameters*/
@parm1 dataType
)
AS
BEGIN
/*Write your select statements below*/
-- SELECT * FROM tblName
-- SELECT * FROM tblName2

END

您必须将这些记录填入您的DataSet,DataSet支持多个表进入ADO.net.

请参考以下代码填写您的DataSet:

SqlConnection con=new SqlConnection("YourConnection String");
SqlCommand cmd=new SqlCommand();
SqlDataAdapter da=new SqlDataAdapter();
DataSet ds = new DataSet();
cmd = new SqlCommand("SPName", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@parm1", id);//if you have parameters.
da = new SqlDataAdapter(cmd);
da.Fill(ds);
con.Close();

在此之后,您可以使用不同的多个记录集

ds.Tables[0]
ds.Tables[1]
..

希望它能帮到你

谢谢

查看更多关于c# – 从sql server存储过程返回多个数据集的详细内容...

  阅读:46次