【SQL 代码】Sql分页(自用)

9/1/2015来源:SQL技巧人气:1432

【SQL 代码】Sql分页(自用)

效果图:

下面是存储过程的创建,用的时候调用就行了

/****** Object:  StoredPRocedure [dbo].[spSqlPageByRownumber]    Script Date: 2015/3/5 17:34:38 ******/SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOCREATE proc [dbo].[spSqlPageByRownumber]@tbName varchar(255),        --表名@tbFields varchar(1000),      --返回字段@PageSize int,                --页尺寸@PageIndex int,                --页码@strWhere varchar(1000),    --查询条件@StrOrder varchar(255)  --排序条件asdeclare @strSql varchar(5000)    --主语句declare @strSqlCount nvarchar(500)----------------总记录数---------------if @strWhere !=''beginset @strSqlCount='Select count(*) as TotalCout from  ' + @tbName + ' where '+ @strWhereendelsebeginset @strSqlCount='Select count(*) as TotalCout from  ' + @tbNameend--------------分页------------if @PageIndex <= 0begin  set @PageIndex = 1endif @strWhere !=''beginset @strSql='Select * from (Select  row_number() over('+@strOrder+') rowId,'+ @tbFields+' from ' + @tbName + ' where  ' + @strWhere+' ) tb where tb.rowId >'+str((@PageIndex-1)*@PageSize)+' and tb.rowId <= ' +str(@PageIndex*@PageSize)endelsebeginset @strSql='Select * from (Select  row_number() over('+@strOrder+') rowId,'+ @tbFields+' from ' + @tbName + ' ) tb where tb.rowId >'+str((@PageIndex-1)*@PageSize)+' and tb.rowId <= ' +str(@PageIndex*@PageSize)endexec(@strSqlCount)exec(@strSql)GO

执行:

exec [dbo].spSqlPageByRownumber 'GoodsCategory','*',10,2,'Cid > 0','order by Cid desc'