SQL Server general paging display stored procedure _ MySQL

Source: Internet
Author: User
The general paging display stored procedure of SQLServer creates a Web application, which is essential for paging browsing. This problem is very common in database processing. The typical data paging method is the ADO record set paging method, that is, using the paging function provided by ADO (using the cursor) to implement paging. However, this paging method is only applicable to small data volumes, because the cursor itself has a disadvantage: the cursor is stored in the memory and is very memory-intensive.

When the game tag is set up, the related records are locked until the cursor is canceled. A cursor provides a method to scan data row by row in a specific set. generally, a cursor is used to traverse data row by row and perform different operations based on different data conditions. For the multi-table and big table-defined cursors (large data sets) loop, it is easy for the program to enter a long wait or even crash.

More importantly, for a very large data model, it is a waste of resources to load the entire data source every time during paging retrieval. Currently, the popular paging method is to retrieve data in the block area of the page size, instead of all the data, and then execute the current row in one step.

The earliest method to extract data based on the page size and page number is probably the "Russian stored procedure ". This stored procedure uses a cursor. due to the limitations of the cursor, this method has not been widely recognized.

Later, someone modified the stored procedure on the internet. the following stored procedure is a paging stored procedure written in conjunction with our office automation instance:

CREATE procedure pagination1
(@ Pagesize int, -- page size, such as storing 20 records per page
@ Pageindex int -- current page number
)
As

Set nocount on

Begin
Declare @ indextable table (id int identity (), nid int) -- define table variables
Declare @ PageLowerBound int -- defines the bottom code of this page.
Declare @ PageUpperBound int -- defines the top code of this page.
Set @ PageLowerBound = (@ pageindex-1) * @ pagesize
Set @ PageUpperBound = @ PageLowerBound + @ pagesize
Set rowcount @ PageUpperBound
Insert into @ indextable (nid) select gid from TGongwen
Where fariqi> dateadd (day,-365, getdate () order by fariqi desc
Select O. gid, O. mid, O. title, O. fadanwei, O. fariqi from TGongwen O, @ indextable t
Where O. gid = t. nid and t. id> @ PageLowerBound
And t. id <= @ PageUpperBound order by t. id
End

The stored procedure above set nocount off uses the latest SQL SERVER Technology-table variables. It should be said that this stored procedure is also a very good paging stored procedure. Of course, in this process, you can also write the TABLE variables as temporary tables: create table # Temp. But it is obvious that in SQL SERVER, using temporary tables does not use quick table variables. So when I first started using this stored procedure, I felt very good and the speed was better than that of the original ADO. But later, I found a better method than this method.

The author once saw a short article on the Internet, "how to retrieve records from the data table from the nth to the nth". The full text is as follows:

Retrieve the n to m records from the publish table:
Select top m-n + 1 *
FROM publish
WHERE (id NOT IN
(Select top n-1 id
FROM publish ))

When I saw this article, the key word of the table whose id is publish is really a boost in spirit, and I think the idea is very good. Later, I was working on an office automation system (ASP. NET + C # + SQL server), suddenly remembered this article, I think if you modify this statement, this may be a very good paging storage process. So I searched for this article on the internet. I did not expect this article to be found, but I found a paging storage process written according to this statement, this storage process is also a popular paging storage process. I regret that I didn't rush to transform this text into a storage process:

Create procedure pagination2
(
@ SQL nVARCHAR (4000), -- SQL statements without sorting statements
@ Page int, -- Page number
@ RecsPerPage int, -- number of records per page
@ Id varchar (255), -- unique ID to be sorted
@ Sort VARCHAR (255) -- Sort fields and rules
)
AS

DECLARE @ Str nVARCHAR (4000)

SET @ Str = ''select TOP ''+ CAST (@ RecsPerPage as varchar (20) + ''' * FROM
(''+ @ SQL +'') T WHERE T. ''+ @ ID +'' not in (select top ''+ CAST (@ RecsPerPage * (@ Page-1 ))
As varchar (20) + ''' + @ ID + ''' FROM (''+ @ SQL +'') T9 ORDER BY ''+ @ Sort + '') order by ''+ @ Sort

PRINT @ Str

EXEC sp_ExecuteSql @ Str
In fact, the preceding statements can be simplified:

Select top page size *
FROM Table1 WHERE (id not in (select top page size * page id FROM table order by id ))
Order by id, but this stored procedure has a fatal disadvantage, that is, it contains not in words. Although I can transform it:

Select top page size *
FROM Table1 WHERE not exists
(Select * from (select top (page size * pages) * from table1 order by id) B where B. id = a. id)
Order by id: Replace not in with not exists. However, we have already discussed that there is no difference in execution efficiency between the two. IN this case, the combination of TOP and not in is faster than using a cursor.

Although using not exists does not save the efficiency of the last stored procedure, using TOP keywords in SQL SERVER is a wise choice. Because the ultimate goal of paging optimization is to avoid generating too many record sets, we have mentioned the TOP advantage in the previous sections. using TOP, we can control the data volume.

IN paging algorithms, there are two key factors that affect the query speed: TOP and not in. TOP can increase our query speed, while not in will slow down our query speed. therefore, to increase the speed of our entire paging algorithm, we need to completely transform not in, replace it with other methods.

We know that we can use max (field) or min (field) to extract the maximum or minimum values of almost any field, so if this field is not repeated, then, we can use the max or min of these non-repeated fields as the watershed to make them a reference object for separating each page in the paging algorithm. Here, we can use the operator ">" or "<" to accomplish this mission, so that the query statement conforms to the SARG format. For example:

Select top 10 * from table1 where id> 200, the following paging scheme is available:

Select top page size *
From table1
Where id>
(Select max (id) from
(Select top (page number-1) * page size) id from table1 order by id) as T
)
When selecting a column with no duplicate values and easy to tell the size of order by id, we usually select a primary key. The following table lists the tables in the office automation system with 10 million data .) For sorting columns and extracting gid, fariqi, and title fields, take pages 1st, 10, 100, 500, 1000, 10 thousand, 0.1 million, and 0.25 million as examples, test the execution speed of the preceding three paging schemes: (unit: milliseconds)

Page number scheme 1 Scheme 2 scheme 3
1 60 30 76
10 46 16 63
100 1076 720 130
500 540 12943 83
1000 17110 470 250
10000 24796 4500 140
100000 38326 42283 1553
250000 28140 128720 2330
500000 121686 127846 7168

From the table above, we can see that the three stored procedures can be trusted when executing paging commands below 100 pages, and the speed is good. However, in the first solution, after more than 1000 pages are executed, the speed will decrease. The second solution is that the speed starts to decrease after more than 10 thousand pages are executed. However, the third solution has never been greatly downgraded, and the stamina is still very strong.

After determining the third paging scheme, we can write a stored procedure accordingly. As you know, the stored procedure of SQL server is compiled in advance, and its execution efficiency is higher than that of SQL statements sent through WEB pages. The following stored procedure not only contains the paging scheme, but also determines whether to make statistics on the total number of data based on the parameters sent from the page.

Obtain data on a specified page:

Create procedure pagination3
@ TblName varchar (255), -- table name
@ StrGetFields varchar (1000) = ''', -- the column to be returned
@ FldName varchar (255) = ''', -- Name of the sorted field
@ PageSize int = 10, -- page size
@ PageIndex int = 1, -- page number
@ DoCount bit = 0, -- returns the total number of records. if the value is not 0, the system returns
@ OrderType bit = 0, -- set the sorting type. if the value is not 0, the sorting type is descending.
@ StrWhere varchar (1500) = ''' -- query condition (note: Do not add where)
AS

Declare @ strSQL varchar (5000) -- subject sentence
Declare @ strTmp varchar (110) -- Temporary variable
Declare @ strOrder varchar (400) -- sort type

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 + "]"
The end code above indicates that if @ doCount is not passed over 0, the total number of statistics will be executed. All the following code is 0 @ doCount:

Else
Begin
If @ OrderType! = 0
Begin
Set @ strTmp = "<(select min"
Set @ strOrder = "order by [" + @ fldName + "] desc" If @ OrderType is not 0, execute the descending order. This sentence is very important!

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 execute the above code on the first page, which will speed up the execution.

End
Else
The following begin Code grants @ strSQL the SQL code to be actually executed

Set @ strSQL = "select top" + str (@ PageSize) + "" + @ strGetFields + "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) + "" + @ strGetFields + "from ["
+ @ TblName + "] where [" + @ fldName + "]" + @ strTmp + "(["
+ @ FldName + "]) from (select top" + str (@ PageIndex-1) * @ PageSize) + "["
+ @ FldName + "] from [" + @ tblName + "] where" + @ strWhere + ""
+ @ StrOrder + ") as tblTmp) and" + @ strWhere + "" + @ strOrder
End

End

Exec (@ strSQL)

GO
The above stored procedure is a general stored procedure, and its annotations have been written in it. In the case of large data volumes, especially when querying the last few pages, the query time generally does not exceed 9 seconds. other stored procedures may cause timeout in practice, therefore, this stored procedure is very suitable for queries of large-capacity databases. I hope that through the analysis of the above stored procedures, we can provide some inspiration and improve the efficiency of our work. at the same time, I hope our peers can propose better real-time data paging algorithms.

In the case of small data volumes, the third stored procedure is as follows:

1. the paging speed is generally between 1 second and 3 seconds.

2. when querying the last page, the speed is generally 5 to 8 seconds, even if the total number of pages is only 3 or 0.3 million pages.

Although the implementation of this paging process is very fast in the case of ultra-large capacity, but in the first few pages, this 1-3 second speed is slower than the first non-optimized paging method. in the user's words, it is "no ACCESS database is faster ", this recognition is sufficient to prevent users from using your developed system.

I have analyzed this. the crux of this problem is so simple, but so important: the sorting field is not a clustered index!

The author does not put together the topics of "query optimization" and "paging algorithm" because both of them need a very important thing-clustered index.

As we mentioned earlier, clustered indexes have two major advantages:

1. narrow the query range as quickly as possible.

2. sort fields as quickly as possible.

1st are mostly used for query optimization, while 2nd are mostly used for data sorting during paging.

Clustered indexes can only be created in one table, which makes clustered indexes more important. The selection of clustered indexes can be said to be the most critical factor for "query optimization" and "efficient paging.

However, clustering index columns must meet both the needs of query columns and the needs of sorting columns. this is usually a contradiction. In my previous "index" discussion, I used fariqi, that is, the user's published date as the starting column of the clustered index. the date accuracy is "day ". The advantages of this method have been mentioned earlier. in the quick query of the time range, it is more advantageous than using the ID primary key column.

However, because duplicate records exist in the clustered index column during pagination, max or min cannot be used as the most paging reference object, thus making sorting more efficient. If the ID primary key column is used as the clustered index, the clustered index is useless except for sorting. In fact, this is a waste of valuable resources.

To solve this problem, I later added a date column, whose default value is getdate (). When a user writes a record, this column automatically writes the current time, accurate to milliseconds. Even so, to avoid a small possibility of overlap, you also need to create a UNIQUE constraint on this column. Use this date column as the clustered index column.

With this time-based clustered index column, you can use this column to query a certain period of time when you insert data, and use it as a unique column to implement max or min, it is a reference object for paging algorithms.

After such optimization, the author found that the paging speed is usually dozens of milliseconds or even 0 milliseconds in the case of large data volumes or small data volumes. However, the query speed for narrowing the range by date segments is no slower than the original query speed. Clustered index is so important and precious, so I have summarized that clustered index must be built on:

1. the most frequently used field to narrow the query scope;

2. the most frequently used field to be sorted.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.