Dynamic soft code generator paging stored procedure

1. Define the paging stored procedure of the dynamic software code generator

-- ---------------------------------- 
-- Purpose: Paging stored procedure (efficiency for tables with primary keys extremely high) --Description 
: ---------------------------------- CREATE PROCEDURE [ dbo ] 
. [ UP_GetRecordByPage ] @tblName varchar ( 255 ),        -- table name @fldName varchar ( 255 ),        -- primary key field name @PageSize int = 10 ,            -- page size @PageIndex int = 1 ,             --
  
          
          
           
          Page number 
    @IsReCount     bit  =  0 ,             -- return the total number of records, non-0 value return 
    @OrderType     bit  =  0 ,             -- set the sort type, non-0 value in descending order 
    @strWhere      varchar ( 1000 ) =  '' , -- query condition ( Note: don't add where) 
    @totalNum  int output
 AS

declare  @strSQL    varchar ( 6000 )        -- the main statement 
declare  @strTmp    varchar ( 100 )         -- temporary variables (may be wrong when the query condition is too long, you can modify 100 to 1000) 
declare  @strOrder  varchar ( 400 )         -- sort type

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

set @strSQL = 'select top ' + str(@PageSize) + ' * from ['
    + @tblName + '] where [' + @fldName + ']' + @strTmp + '(['
    + @fldName + ']) from (select top ' + str((@PageIndex-1)*@PageSize) + ' ['
    + @fldName + '] from [' + @tblName + ']' + @strOrder + ') as tblTmp)'
    + @strOrder

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

if @PageIndex = 1
begin
    set @strTmp =''
    if @strWhere != ''
        set @strTmp = ' where ' + @strWhere

    set @strSQL = 'select top ' + str(@PageSize) + ' * from ['
        + @tblName + ']' + @strTmp + ' ' + @strOrder
end

 --获取记录总数
DECLARE @strCountSql NVARCHAR(1000);
SET @strCountSql = 'Select @RecordCount = count(1) FROM '+@tblName+' WHERE 1 = 1 ' + @strWhere
EXEC sp_executesql @strCountSql, N'@RecordCount int OUTPUT', @totalNum OUTPUT

exec (@strSQL)

GO

 

2. Points to pay attention to when writing

(1) After defining the @strWhere variable, it should be initialized in time.

(2) When splicing SQL conditions, pay attention to include field values ​​with ''.

(3) The time variable should be converted into a string in a specific format

(4) EXEC()

(5) EXEC sp_executesql

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325343559&siteId=291194637