1.直接上练习的存储过程,方便回想
create proc proc_output
@totlecount int output,
@pageIndex int,
@pageSize int
as
declare @filter Nvarchar(800)
if OBJECT_ID(‘Test.dbo.#temp3′,’U’) IS NOT NULL
begin
drop table #temp3
end
set @filter=’select identity(int,1,1) as id,* into #temp3 from (
select name from t1 group by name
) as table2;
select * from #temp3 where id between ‘+CONVERT(VARCHAR(8),(@pageSize*(@pageIndex-1)+1))+’ and ‘+CONVERT(VARCHAR(8),@pageIndex*@pageSize)+’;
select @Count=count(1) from #temp3′
exec sp_executesql @filter,N’@Count int output’,@totlecount output
2.在执行这个存储过程时,报错:
消息 214,级别 16,状态 2,过程 sp_executesql,第 3 行
过程需要类型为 ‘ntext/nchar/nvarchar’ 的参数 ‘@statement’。
原因是:需要将定义的@filter 定义为Nvarchar类型,当定义为varchar时会出现上述错误。
3.在数据库执行存储过程的结果:
4.原本的想法是:数据库进行了复杂的查询(当进行多表联合查询以及select查询拼接新表时)得到临时表,
想省去一个单独查询符合分页条件总数量的存储过程原因是要进行相同的临时表创建,当数据量特别大时页面相应的时间
会比较长。现实是读数据需要调用ExecuteReader方法读取数据,想要得到output参数需要调用ExecuteNonQuery方法得到
输出参数。当调用ExecuteReader方法时,DAL层 param[0].Direction = ParameterDirection.Output;
totleCount =param[0].Value == DBNull.Value ? 0 : Convert.ToInt32(param[0].Value); 这时候的param[0].Value 值为null;
当再调用ExecuteNonQuery方法时,会得到6;(作为一个坑总结一下)
5.那么问题出来了 ,还是调用了两次同一个存储过程,换句话说数据库的查询量并没有减少………..
6.于是乎在返回的表里临时添加了一列,记录符合条件的总的信息条数。
将存储过程的“select * from #temp3 where id between ‘+CONVERT(VARCHAR(8),(@pageSize*(@pageIndex-1)+1))+’ and ‘+CONVERT(VARCHAR(8),@pageIndex*@pageSize)+’;
select @Count=count(1) from #temp3” 修改为了“select * ,
(select count(1) from #temp3) as totleCount
from #temp3 where id between ‘+CONVERT(VARCHAR(8),(@pageSize*(@pageIndex-1)+1))+’ and ‘+CONVERT(VARCHAR(8),@pageIndex*@pageSize)+’”
这样调用ExecuteReader方法时,就会得到符合查询条件的信息条数。缺点是返回的每一条数据都有这个信息。
所以需要判断得到list的长度,当>0时,获取list[0].totleCount即是总条数否则为0
7.修改完成的存储过程
alter proc proc_output
@pageIndex int,
@pageSize int
as
declare @filter Nvarchar(800)
if OBJECT_ID(‘Test.dbo.#temp3′,’U’) IS NOT NULL
begin
drop table #temp3
end
set @filter=’select identity(int,1,1) as id,* into #temp3 from (
select name from t1 group by name
) as table2;
select *,(select count(1) from #temp3) as totleCount from #temp3 where id between ‘+CONVERT(VARCHAR(8),(@pageSize*(@pageIndex-1)+1))+’ and ‘+CONVERT(VARCHAR(8),@pageIndex*@pageSize)+’;
‘
exec (@filter)
8.执行结果: