zoukankan      html  css  js  c++  java
  • MSSQL通用分页过程

    USE [AiFashionDining]
    GO

    /****** Object: StoredProcedure [dbo].[pv_page_search] Script Date: 04/04/2018 18:20:07 ******/
    SET ANSI_NULLS ON
    GO

    SET QUOTED_IDENTIFIER ON
    GO

    CREATE PROCEDURE [dbo].[pv_page_search]
    @tblName varchar(max), -- 表名'
    @strGetFields varchar(1000) = '*', -- 需要返回的列
    @fldName varchar(255)='', -- 排序的字段名
    @PageSize int = 10, -- 页尺寸
    @PageIndex int = 1, -- 页码
    @doCount bit = 1, -- 返回记录总数, 非 0 值则返回
    @OrderType bit = 0, -- 设置排序类型, 非 0 值则降序
    @strWhere varchar(1500) = '' -- 查询条件 (注意: 不要加 where)
    AS

    declare @strSQL varchar(5000) -- 主语句
    declare @strTmp varchar(110) -- 临时变量
    declare @strOrder varchar(400) -- 排序类型
    declare @strCheck varchar(400) --处理两表比对字段同名时出现的问题,直接取.后面的字段名做为变量

    select @strCheck=substring(@fldName,CHARINDEX('.',@fldName)+1,LEN(@fldName))

    if @doCount != 0
    begin
    if @strWhere !=''
    set @strSQL = 'select count(*) as Total from ' + @tblName + ' where '+@strWhere
    else
    set @strSQL = 'select count(*) as Total from ' + @tblName + ' '
    end
    else
    begin
    if @OrderType != 0
    begin
    set @strTmp = '<(select min'
    set @strOrder = ' order by ' + @fldName +' desc'
    end
    else
    begin
    set @strTmp = '>(select max'
    set @strOrder = ' order by ' + @fldName +' asc'
    end

    if @PageIndex = 1
    begin
    if @strWhere != ''

    set @strSQL = 'select top ' + str(@PageSize) +' '+@strGetFields+ '
    from ' + @tblName + ' where ' + @strWhere + ' ' + @strOrder
    else

    set @strSQL = 'select top ' + str(@PageSize) +' '+@strGetFields+ '
    from '+ @tblName + ' '+ @strOrder
    end
    else
    begin
    set @strSQL = 'select top ' + str(@PageSize) +' '+@strGetFields+ ' from '
    + @tblName + ' where ' + @fldName + '' + @strTmp + '('+ @strCheck + ')
    from (select top ' + str((@PageIndex-1)*@PageSize) + ' '+ @fldName + '
    from ' + @tblName + '' + @strOrder + ') as tblTmp)'+ @strOrder
    if @strWhere != ''
    set @strSQL = 'select top ' + str(@PageSize) +' '+@strGetFields+ ' from '
    + @tblName + ' where ' + @fldName + ' ' + @strTmp + '('
    + @strCheck + ') from (select top ' + str((@PageIndex-1)*@PageSize) + ' '
    + @fldName + ' from ' + @tblName + ' where ' + @strWhere + ' '
    + @strOrder + ') as tblTmp) and ' + @strWhere + ' ' + @strOrder
    end

    end

    print(@strSQL)

    exec (@strSQL)


    GO

  • 相关阅读:
    影响cpu性能的因素有哪些?
    linux系统中 SElinux安全子系统
    linux 系统中个人用户主页功能
    理解 Segmentation fault
    VI高级命令集锦
    How to be a Star 怎样成为明星?
    名词解释:DEADBEEF
    Unix还能走多远?
    Awk 实例,第 1 部分
    77年出生的朋友,你们过的还好吗?
  • 原文地址:https://www.cnblogs.com/maweiwei/p/11898059.html
Copyright © 2011-2022 走看看