标签:检查 分页显示 varchar top char ble tor ring tom
USE [LH_Kes]
GO
/****** Object: StoredProcedure [dbo].[ProcCustomPage] Script Date: 07/10/2019 17:47:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[ProcCustomPage]
(
@TableName nvarchar(100), --要分页显示的表名
@KeyFields nvarchar(1000), --用于定位记录的主键(惟一键)字段,可以是逗号分隔的多个字段
@PageIndex int=1, --要显示的页码
@PageSize int=20, --每页的大小(记录数)
@ShowFields nvarchar(1000)=‘‘, --以逗号分隔的要显示的字段列表,如果不指定,则显示所有字段
@OrderFields nvarchar(1000)=‘‘, --以逗号分隔的排序字段列表,可以指定在字段后面指定DESC/ASC
@WhereString nvarchar(4000)=‘‘, --查询条件,不要加WHERE
@RecordCount int OUTPUT --总页数
)
AS
SET NOCOUNT ON
--分页字段检查
IF ISNULL(@KeyFields,N‘‘)=‘‘
BEGIN
RAISERROR(N‘分页处理需要主键(或者惟一键)‘,1,16)
RETURN
END
--其他参数检查及规范
IF ISNULL(@PageIndex,0)<1 SET @PageIndex=1
IF ISNULL(@PageSize,0)<1 SET @PageSize=10
IF ISNULL(@ShowFields,N‘‘)=N‘‘ SET @ShowFields=N‘*‘
IF ISNULL(@OrderFields,N‘‘)=N‘‘
SET @OrderFields=N‘‘
ELSE
SET @OrderFields=N‘ORDER BY ‘+LTRIM(@OrderFields)
IF ISNULL(@WhereString,N‘‘)=N‘‘
SET @WhereString=N‘‘
ELSE
SET @WhereString=N‘WHERE (‘+@WhereString+N‘)‘
--如果@RecordCount为NULL值,则计算总页数(这样设计可以只在第一次计算总页数,以后调用时,把总页数传回给存储过程,避免再次计算总页数,对于不想计算总页数的处理而言,可以给@RecordCount赋值)
IF @RecordCount IS NULL
BEGIN
DECLARE @sql nvarchar(4000)
SET @sql=N‘SELECT @RecordCount=COUNT(*)‘
+N‘ FROM ‘+@TableName
+N‘ ‘+@WhereString
EXEC sp_executesql @sql,N‘@RecordCount int OUTPUT‘,@RecordCount OUTPUT
END
--计算分页显示的TOPN值
DECLARE @TopN varchar(20),@TopN1 varchar(20)
SELECT @TopN=@PageSize,
@TopN1=(@PageIndex-1)*@PageSize
--第一页直接显示
IF @PageIndex=1
EXEC(N‘SELECT TOP ‘+@TopN
+N‘ ‘+@ShowFields
+N‘ FROM ‘+@TableName
+N‘ ‘+@WhereString
+N‘ ‘+@OrderFields)
ELSE
BEGIN
--处理别名
IF @ShowFields=N‘*‘
SET @ShowFields=N‘a.*‘
--生成主键(惟一键)处理条件
DECLARE @Where1 nvarchar(4000),@Where2 nvarchar(4000),
@s nvarchar(1000),@Field sysname
SELECT @Where1=N‘‘,@Where2=N‘‘,@s=@KeyFields
WHILE CHARINDEX(N‘,‘,@s)>0
SELECT @Field=LEFT(@s,CHARINDEX(N‘,‘,@s)-1),
@s=STUFF(@s,1,CHARINDEX(N‘,‘,@s),N‘‘),
@Where1=@Where1+N‘ AND a.‘+@Field+N‘=b.‘+@Field,
@Where2=@Where2+N‘ AND b.‘+@Field+N‘ IS NULL‘,
@WhereString=REPLACE(@WhereString,@Field,N‘a.‘+@Field),
@OrderFields=REPLACE(@OrderFields,@Field,N‘a.‘+@Field),
@ShowFields=REPLACE(@ShowFields,@Field,N‘a.‘+@Field)
SELECT @WhereString=REPLACE(@WhereString,@s,N‘a.‘+@s),
@OrderFields=REPLACE(@OrderFields,@s,N‘a.‘+@s),
@ShowFields=REPLACE(@ShowFields,@s,N‘a.‘+@s),
@Where1=STUFF(@Where1+N‘ AND a.‘+@s+N‘=b.‘+@s,1,5,N‘‘),
@Where2=CASE
WHEN @WhereString=‘‘ THEN N‘WHERE (‘
ELSE @WhereString+N‘ AND (‘
END+N‘b.‘+@s+N‘ IS NULL‘+@Where2+N‘)‘
--执行查询
EXEC(N‘SELECT TOP ‘+@TopN
+N‘ ‘+@ShowFields
+N‘ FROM ‘+@TableName
+N‘ a LEFT JOIN(SELECT TOP ‘+@TopN1
+N‘ ‘+@KeyFields
+N‘ FROM ‘+@TableName
+N‘ a ‘+@WhereString
+N‘ ‘+@OrderFields
+N‘)b ON ‘+@Where1
+N‘ ‘+@Where2
+N‘ ‘+@OrderFields)
END
标签:检查 分页显示 varchar top char ble tor ring tom
原文地址:https://www.cnblogs.com/wxm0827/p/11165484.html