http://www.cnblogs.com/kacoro/archive/2011/06/08/2075594.html
上文中的代码确实能用,不过有个问题就是我不明白作者在.cs代码中,为何把where给注释掉,自己尝试后发现在运行存储过程时,当@SelectWhere不为空就会出错。查了下代码,既然提示不需要手动添加where关键词,sql语句自然需要有,而上文的存储过程中却没发现。最后改成如下:
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
ALTER proc [dbo].[getdataset]
@TableList Varchar(200)='*',--搜索表的字段,比如:’id,datatime,job‘,用逗号隔开
@TableName Varchar(30), --搜索的表名
@SelectWhere Varchar(500)='',--搜索条件,这里不用写where,比如:job=’teacher‘and class='2'
@SelectOrderId Varchar(20),--表主键字段名。比如:id
@SelectOrder Varchar(200)='', --排序,可以使用多字段排序但主键字段必需在最前面.也可以不写,比如:order by class asc
@intPageNo int=1, --页号
@intPageSize int=10 ,--每页显示数
@RecordCount int OUTPUT --总记录数(存储过程输出参数)
as
declare @TmpSelect NVarchar(600)
declare @Tmp NVarchar(600)
set nocount on--关闭计数
if @SelectWhere != ''
set @TmpSelect = 'select @RecordCount = count(*) from '+@TableName+' where '+@SelectWhere
else
set @TmpSelect = 'select @RecordCount = count(*) from '+@TableName+' '+@SelectWhere
execute sp_executesql @TmpSelect, --执行上面的sql语句
N'@RecordCount int OUTPUT' , --执行输出数据的sql语句,output出总记录数
@RecordCount OUTPUT if (@RecordCount = 0) --如果没有贴子,则返回零
return 0
/*判断页数是否正确*/
if (@intPageNo - 1) * @intPageSize > @RecordCount --页号大于总页数,返回错误
return (-1)
set nocount off --打开计数
if @SelectWhere != ''
begin
set @TmpSelect = 'select top '+str(@intPageSize)+' '+@TableList+' from '+@TableName+' where '+@SelectOrderId+' not in(select top '+str((@intPageNo-1)*@intPageSize)+' '+@SelectOrderId+' from '+@TableName+' where '+@SelectWhere +' '+@SelectOrder+') and '+@SelectWhere +' '+@SelectOrder
end
else
begin
set @TmpSelect = 'select top '+str(@intPageSize)+' '+@TableList+' from '+@TableName+' where '+@SelectOrderId+' not in(select top '+str((@intPageNo-1)*@intPageSize)+' '+@SelectOrderId+' from '+@TableName+' '+@SelectOrder+') '+@SelectOrder
end
execute sp_executesql @TmpSelect
return(@@rowcount)
50W条记录,浏览时很快。
原文地址http://www.cnblogs.com/kacoro/archive/2011/06/09/2076110.html#