3. How to optimize the operation of a large data database (realize the paging display and storage process of small data volume and massive data)

Source: Internet
Author: User
Tags rowcount

Iii. General paging display and storage process for small data volumes and massive data

Creating a web application requires paging. This problem is very common in database processing. The typical data paging method is the ADO record set paging method, that is, pagination is achieved by using the ADO self-contained paging function (using the cursor. 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

Set nocount off

The above stored procedures use 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 ))

Keywords with ID publish table

When I saw this article at the time, I was truly inspired by the spirit and thought that the idea was 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 found this article on the Internet. I did not expect that the article was not found yet, 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
GO

In fact, the preceding statement 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

However, this stored procedure has a fatal drawback, that 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

That is to say, not exists is used to replace not in, but we have already discussed that there is no difference in the 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 solution 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

)

Order by id

When selecting a column with no repeated values and easy to tell the size, we usually select a primary key. The following table lists the tables in my office automation system that uses 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 code
Solution 1
Solution 2
Solution 3

1
60
30
76

10
46
16
63

100
1076
720
130

500
540
12943
83

1000
17110
470
250

10 thousand
24796
4500
140

0.1 million
38326
42283
1553

0.25 million
28140
128720
2330

0.5 million
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.

-- Get 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 + "]"

End

-- The above Code indicates that if @ docount is not passed over 0, the total number of statistics will be executed. All the code below 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

Begin

-- The following code gives @ 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.

Iii. General paging display and storage process for small data volumes and massive data

Creating a web application requires paging. This problem is very common in database processing. The typical data paging method is the ADO record set paging method, that is, pagination is achieved by using the ADO self-contained paging function (using the cursor. 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

Set nocount off

The above stored procedures use 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 ))

Keywords with id publish table

When I saw this article at the time, I was truly inspired by the spirit and thought that the idea was 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 found this article on the Internet. I did not expect that the article was not found yet, 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
GO

In fact, the preceding statement 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

However, this stored procedure has a fatal drawback, that 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

That is to say, not exists is used to replace not in, but we have already discussed that there is no difference in the 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 solution 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

)

Order by id

When selecting a column with no repeated values and easy to tell the size, we usually select a primary key. The following table lists the tables in my office automation system that uses 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 code
Solution 1
Solution 2
Solution 3

1
60
30
76

10
46
16
63

100
1076
720
130

500
540
12943
83

1000
17110
470
250

10 thousand
24796
4500
140

0.1 million
38326
42283
1553

0.25 million
28140
128720
2330

0.5 million
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.

-- Get 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 + "]"

End

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

Begin

-- The following code gives @ 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.

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.