使用SQL存储过程返回多结果集怎么处理
存储过程里有若干个selec和返回参数:
@z_count int output,
@z_sum int output
AS
BEGIN
select @z_count=Count(*) from news_tab
select @z_sum=sum(click) from news_Tab
select classFir,count(*) from news_tab group by classFir
END
这样多样式的结果集前台怎么处理阿???
------解决方案--------------------把结果fill到一个DataTable里面
在根据需要取DataTable取
------解决方案--------------------如果有多个结果集返回,那么客户端一定要用一个DataSet来接收才行,这样可以通过DataSet的.Tables来分别访问它返回的数据集了.
------解决方案--------------------dataset 和OUTPUT 一起用.
------解决方案--------------------你把你的Sql改一下:
@z_count int output,
@z_sum int output
AS
BEGIN
set @z_count=Count(*) from news_tab
set @z_sum=sum(click) from news_Tab
select classFir,count(*) from news_tab group by classFir
END
-----------------------
细看了一下你的存储过程,觉得你最好看上面的改一下,这样就只会返回最后个的select结果了,而上面的两个就用output输出了.
------解决方案--------------------SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
GridView1.DataSource = dr;
GridView1.DataBind();
}
if (dr.NextResult())
{
GridView2.DataSource = dr;
GridView2.DataBind();
}
....
------解决方案--------------------有几条查询语句就有几个table
放到DataSet 里面取就行了
------解决方案--------------------store procedure:
_________________________________________________
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
ALTER proc [dbo].[outputParms]
(
@count int output,
@sum int output
)
AS
BEGIN
declare @t table(id int identity(1,1), value int)
insert into @t
select 10 union all
select 20 union all
select 30
select @count = count(1), @sum = sum(value) from @t
select * from @t
END
.cs:
_________________________________________________
protected void Page_Load(object sender, EventArgs e)
{
SqlParameter[] parms = new SqlParameter[2];
parms[0] = new SqlParameter( "@count ",SqlDbType.Int);
parms[0].Direction=ParameterDirection.Output;
parms[1] = new SqlParameter( "@sum ", SqlDbType.Int);
parms[1].Direction = ParameterDirection.Output;
string strConn = @ "server=EN0075\SQLEXPRESS; database=test; uid=reader; pwd=reader; ";
DataTable dt = SqlHelper.ExecuteDataset(strConn, CommandType.StoredProcedure, "outputParms ", parms).Tables[0];
Response.Write( "parms[0].Value: " + parms[0].Value.ToString() + " <br> ");
Response.Write( "parms[1].Value: " + parms[1].Value.ToString() + " <br> ");
for (int i = 0; i <dt.Rows.Count ; i++)
{
Response.Write( "Rows " + Convert.ToInt16(i +1).ToString() + ": " + dt.Rows[i][1].ToString() + " <br> ");
}
}
------解决方案--------------------需要注意一点如果是有DataReader接收那么返回值只有在你的连接关闭后才能得到,否则你只能得到结果集output参数是得不到的!
而用DataSet就比较方便,一个DataSet里面可以存N多DataTable你的每一个查询语句返回的结果集会分别存在不同的DataTable里面,用ds.Table[i]可以很方便的访问