分页用存储过程实现
---分页 存储过程
drop table S_INFO
CREATE TABLE S_INFO
(
s_id nvarchar(20) NULL,
s_name nvarchar(20) NULL,
s_sex nchar(1) NULL
)
INSERT INTO dbo.S_INFO(s_id,s_name,s_sex)
VALUES('1','张三丰','男');
INSERT INTO dbo.S_INFO(s_id,s_name,s_sex)
VALUES('2','周芷若','女');
INSERT INTO dbo.S_INFO(s_id,s_name,s_sex)
VALUES('3','宋青书','男');
INSERT INTO dbo.S_INFO(s_id,s_name,s_sex)
VALUES('4','王力宏','男');
INSERT INTO dbo.S_INFO(s_id,s_name,s_sex)
VALUES('5','周杰伦','男');
INSERT INTO dbo.S_INFO(s_id,s_name,s_sex)
VALUES('6','金毛狮王','男')
select * from S_INFO
--获得记录数
GO
DECLARE @TEMP NVARCHAR(500)
DECLARE @TABLENAME NVARCHAR(50)
DECLARE @COUNT INT
SET @TABLENAME = N'S_INFO'
SET @TEMP=N' SELECT @A=COUNT(*) FROM '+@TABLENAME
EXEC SP_EXECUTESQL @TEMP,N'@A INT OUTPUT',@COUNT OUTPUT
SELECT @COUNT
--分页PROC
IF OBJECT_ID('PAGE') IS NOT NULL
DROP PROC PAGE
GO
CREATE PROC PAGE
@TABLENAME VARCHAR(20),
@COLUMN VARCHAR(20),
@CURRENTPAGE INT=1,
@COUNT INT=10,
@COUNTOFPAGE INT OUTPUT
AS
DECLARE @SQL NVARCHAR(1000)
SET @SQL=N'SELECT TOP '+CAST(@COUNT AS NVARCHAR(3))
SET @SQL=@SQL+N' * FROM '+@TABLENAME+' WHERE '+@COLUMN
SET @SQL=@SQL+N' NOT IN (SELECT TOP '+CAST(@COUNT*(@CURRENTPAGE-1) AS NVARCHAR(3))
SET @SQL=@SQL+' '+@COLUMN+N' FROM '+@TABLENAME+' )'
EXEC (@SQL)
DECLARE @SQL2 NVARCHAR(500)
SET @SQL2=N'SELECT @A=COUNT(*) FROM '+@TABLENAME
EXEC SP_EXECUTESQL @SQL2,N'@A INT OUTPUT',@COUNTOFPAGE OUTPUT
SET @COUNTOFPAGE=(@COUNTOFPAGE+@COUNT-1)/@COUNT
--执行分页PROC
GO
DECLARE @COUNTOFPAGES INT
EXEC PAGE 'S_INFO','S_ID',1,3,@COUNTOFPAGES OUTPUT
SELECT @COUNTOFPAGES AS 页数