Analysis of paging Stored Procedure instances (1)

Source: Internet
Author: User

I recently modified a paging storage process. As a newbie, I still benefited a lot from it. Now I will start my paging journey today.

1. Start Restoration

Next, let's take a look at the original paging stored procedure.

 
 
  1. Alter procedure [dbo]. [sp_ SQL _Paging]
  2. (
  3. @ SqlDataTable NVARCHAR (4000), -- table name
  4. @ PrimaryKey NVARCHAR (4000), -- primary key name
  5. @ Fields NVARCHAR (4000), -- the field to be returned
  6. @ PageSize INT, -- page size
  7. @ PageIndex INT, -- page number
  8. @ RecordCount int output, -- total number of records
  9. @ StrOrderBy NVARCHAR (4000), -- Sort
  10. @ StrWhere NVARCHAR (4000) -- Query Condition
  11. )
  12. AS
  13. BEGIN
  14. SET NOCOUNT ON
  15. DECLARE @ strSQL1 NVARCHAR (4000) -- SQL statement 1
  16. DECLARE @ strSQL2 NVARCHAR (4000) -- SQL statement 2
  17.  
  18. -- Create a temporary table
  19. -- Used to save the table number and primary key
  20. Create table # Temp_Paging
  21. (
  22. Temp_Paging_Id INT,
  23. RowNumber INT
  24. )
  25. SET @ strSQL1 = 'insert INTO [# Temp_Paging] (Temp_Paging_Id, RowNumber) select' + @ PrimaryKey + ', ROW_NUMBER () OVER (' + @ strOrderBy + ') AS RowNumber FROM '+ @ SqlDataTable + ''+ @ strWhere
  26. EXEC SP_EXECUTESQL @ strSQL1
  27. SET @ recordCount = @ ROWCOUNT -- get the total number of records
  28. -- Determine the page index
  29. IF @ pageIndex> @ recordCount * 1.0/@ pageSize + 1.0 OR @ recordCount <= @ pageSize
  30. BEGIN
  31. SET @ pageIndex = 1
  32. END
  33. -- Paging Query
  34. SET @ strSQL2 = 'select' + @ Fields + 'from' + @ sqlable able + 'where' + @ PrimaryKey + 'IN (SELECT Temp_Paging_Id FROM [# Temp_Paging] WHERE RowNumber BETWEEN' + str (@ pageIndex-1) * @ pageSize + 1) + 'and' + Str (@ pageIndex * @ pageSize) + ')' + @ strOrderBy
  35. EXEC SP_EXECUTESQL @ strSQL2
  36. Drop table # Temp_Paging -- delete a temporary TABLE
  37. END

It is easy to see from the original paging storage process that the temporary table Storage number is used here, and then calculated by pageIndex and pageSize, paging is performed.

Because the primary key is used as the query condition, the primary key value is also saved in the temporary table.

Obviously, the temporary table here cannot be universal, because the primary key type is not necessarily the INT type defined above, or it can be another type, such as uniqueidentifier (globally unique identifier ).

In this case, the stored procedure encountered a problem and must be improved.

2. Train of Thought 1

The idea is simple. Declare this type as a variable, and then use the system table to obtain the primary key type of the table and assign it to the variable. It looks wonderful. Try it first.

We can insert the following code:

 
 
  1. DECLARE @ colType NVARCHAR (50) -- primary key column type
  2. DECLARE @ strSQL3 NVARCHAR (500) -- create a temporary TABLE statement
  3.  
  4. SET @ colType = (SELECT typ. name as Data Type
  5. FROM sys. columns col
  6. Left join sys. types typ
  7. On (col. system_type_id = typ. system_type_id AND col. user_type_id = typ. user_type_id)
  8. WHERE col. object_id = (SELECT object_id FROM sys. tables WHERE name = @ SqlDataTable)
  9. And exists
  10. (SELECT 1 FROM sys. indexes idx
  11. Join sys. index_columns idxCol
  12. On (idx. object_id = idxCol. object_id)
  13. WHERE idx. object_id = col. object_id
  14. AND idxCol. index_column_id = col. column_id
  15. AND idx. is_primary_key = 1
  16. ))
  17.  
  18. SET @ strSQL3 = 'create TABLE # Temp_Paging
  19. (
  20. Temp_Paging_Id '+ @ colType + ',
  21. RowNumber INT
  22. )'
  23. PRINT @ strSQL3
  24. -- EXEC (@ strSQL3)

Print result:

 
 
  1. CREATE TABLE #Temp_Paging 
  2.                 ( 
  3.                     Temp_Paging_Id uniqueidentifier, 
  4.                     RowNumber INT  
  5.                 ) 

Obviously, we have obtained the required temporary table. At this time, I was very happy because I got what I wanted. But it seems that it is not over yet. I want to execute this stored procedure.

Bad results often appear at this moment:

This is a strange thing. It is clear that the printed statements are correct to create a temporary table, and they are also executed. Why is the subsequent operations on the temporary table invalid?

Ask your colleagues for information and finally understand that the original temporary table is divided into local temporary tables and global temporary tables. Pay attention to the actual deletion time of the local temporary table.

To put it simply, when using EXEC (@ strSQL3) to create a temporary table, the temporary table has been deleted. Because the session in the EXEC process has ended, the temporary table is deleted.

Here is a blog post that gives a more detailed explanation. For details, refer to: SQL temporary tables.


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.