Vous êtes sur la page 1sur 49

HOME

Paging stored procedure


2017-12-28 / VIEWS: 22
Record some of the tool stored procedures that you have used before, and you have to use almost
everything you need to write a page! A paged query stored procedure sqlServer, if there are other
databases in the future, come back and modify!
SqlServer paging stored procedure:

CREATE PROC [dbo].[GlobalPage]

@tab nvarchar ( max ), - - the table name

@strFld nvarchar ( max ), - field string

@strWhere VARCHAR ( max ), - WHERE condition

@PageIndex int , - page

@PageSize int , - per The number of records

held @Sort VARCHAR ( 255 ), -- sort fields and rules, without adding
order by

@Count INT OUTPUT -- return the total number of records

AS

declare @strSql nvarchar(max)

declare @Exec_sql nvarchar(max)


set nocount on;

/* 查詢總記錄數*/

SET @Exec_sql='Set @Count=(SELECT COUNT(0) FROM ' + @tab + ' WHERE


' + @strWhere+' )'

EXEC sp_executesql @Exec_sql,N'@Count int output',@Count output

set @strSql=' SELECT * FROM (SELECT ROW_NUMBER()

OVER(ORDER BY ' + @Sort + ') AS rownum, ' + @strFld + ' FROM ' +
@tab + ' where ' + @strWhere + ') AS Dwhere

WHERE rownum BETWEEN ' + CAST(((@PageIndex-1)*@PageSize + 1) as


nvarchar(20)) + ' and ' + cast((@PageIndex*@PageSize) as nvarchar(20))

exec (@strSql)

set nocount off;

HOME
A universal stored procedure for millions of data
query paging operations
2018-04-20 / VIEWS: 29
I. Introduction

Recently, I have been busy with work, so I rarely write anything. The MongoDB series
of articles has to be delayed. There is no way, work first, no food, no food. It’s just a little bit of
time today, I’ve made some things about me recently and recorded them.

In the software industry, a slightly larger company, the amount of relevant data storage
may be very large, when we do the system, we will use the stored procedure for page display, as
to why the page display, I do not have to say more. Recently, I am working on a system. In order
to let the system support large data volume, I have done a lot of tests, mainly to test the pros and
cons of various paging algorithms. Finally, after many tests, I determined this stored
procedure. The test environment is:
hardware environment: CPU is 12 cores, memory is 8G size,
software environment: Visual Studio 2015, database is Sql Server
2008 R2, data volume is about 30 million
ORM environment: IBatis.Net

The test results are not mapped. If you want to test, you can operate it yourself. First of
all, if you want to query the ID primary key, you can display the paging data for up to 300-400
milliseconds. The first page or the last page shows that the time is similar. In addition, if it is a
query paging for other fields, an index must be created for the field, and the query speed can also
be completed in milliseconds. After many rounds of testing, the final stored procedure style is
determined. Of course, if there is no index page for the paged field of the query, the time will be
longer. 6 minutes, 10 minutes is possible. Since only the stored procedure is discussed today, the
others will not be discussed, such as sub-library, sub-table, horizontal split or vertical split.

Second, the stored procedure code

Of course, this stored procedure also refers to the information of many seniors, only to
finalize. Modified its original bug, and some errors in the grammar hill. Other details have also
been fine-tuned to form this final version. If you have a better way of writing, you are welcome
to leave a message. Not much nonsense, the code is sent out today, the stored procedure has been
tested, no problem at all, you can rest assured to use, the code is as follows:
1 USE [XXXXXXXX .BbbbbbbbCcccccccc.Dataware ]

2 GO

3 /* ***** Object: StoredProcedure


[dbo].[usp_CommonDataResourcePaged] Script Date: 2018/4/20 9:01:14
***** */
4 SET ANSI_NULLS ON

5 GO

6 SET QUOTED_IDENTIFIER ON

7 GO

8 -- ============================================= =========

9 -- Author: <PatrickLiu>

10 -- Create date: <2018-4-16 14:21>

11 -- Description: <Universal data paging stored procedure>

12 --=============================================

13= ALTER PROCEDURE [ dbo ] . [ usp_CommonDataResourcePaged ]

14 (

15 @tablename nvarchar ( 200 is ), - - or


is connected to display a plurality of tables table

16 @FieldList nvarchar ( 1500 ) = ' * ' , - - the


list of fields to be displayed

17 @PageSize int = 20 , -- --

Number of records per page 18 @PageNumber int = 1 ,


-- -- To display the record for that page

19 @SortFields nvarchar ( 1000 ) = null , -- -- Sort


field list or condition

20 @EnabledSort bit = 0 , -- -- Sort


method, 0 is ascending , 1 is descending (if the multi-field
arrangement Sort refers to the order of the last sort field (the last
sort field is not sorted) - the process pass parameters such as:
'SortA Asc, SortB Desc, SortC ')

21 @QueryCondition Nvarchar ( 1500 ) = null , -- --


query condition, no WHERE

22 @Primarykey nvarchar ( 50 ), -- -- The


primary key of the main table

23 @EnabledDistinct bit = 0 , -- --
Whether to add the DISTINCT of the query field Default 0 does not add
/1 Add

24 @PageCount int = 1 output, -- -- Query


results after the total page Page

25 @RecordCount int = 1 output -- -- Number


of records queried

26 )

27 AS

28 SET NOCOUNT ON

29 Declare @SqlResult nvarchar ( 1000 ) -- -- Store


dynamically generated SQL statements

30 Declare @SqlTotalCount nvarchar ( 1000 ) -- -- Store


the query statement that

gets the total number of query results 31 Declare


@SqlStartOrEndID nvarchar ( 1000 ) -- -- Store the query
that

gets the start or end ID of the query 32

33 Declare @SortTypeA nvarchar ( 10 ) -- --Data Sorting


Rule A

34 Declare @SortTypeB nvarchar ( 10 ) -- -- Data Sorting


Rule B
35

36 Declare @SqlDistinct nvarchar ( 50 ) -- -- SQL


construction of the query containing DISTINCT

37 Declare @SqlCountDistinct nvarchar ( 50 ) -- --


SQL construction of the total query containing DISTINCT

38

39 declare @ timediff datetime -- time

- consuming test time difference 40 SELECT @ timediff = getdate


()

41 is

42 is IF @EnabledDistinct = 0

43 is the begin

44 is SET @SqlDistinct = ' the SELECT '

45 SET @SqlCountDistinct = ' the Count (*)'

46 end

47 else

48 begin

49 set @SqlDistinct = ' SELECT DISTINCT '

50 set @SqlCountDistinct = ' Count(DISTINCT ' +


@Primarykey + ' ) '

51 end

52
53 if @EnabledSort = 0

54 begin

55 set @SortTypeB = ' ASC '

56 set @SortTypeA = ' DESC'

57 end

58 else

59 begin

60 set @SortTypeB = ' DESC '

61 set @SortTypeA = ' ASC '

62 end

63

64 -- ------ Generate query statement --------

65 -- this to achieve results at @SqlTotalCount number of


statements

66 IF @QueryCondition iS null or @QueryCondition = '' -


did not set the display condition

67 the begin

68 the sET @SqlResult = @FieldList + ' From ' +


@TableName

69 set @SqlTotalCount = @SqlDistinct + ' @RecordCount=


' + @SqlCountDistinct + ' FROM ' + @TableName

70 set @SqlStartOrEndID = ' From ' + @TableName


71 end

72 else

73 begin

74 set @ SqlResult = + @FieldList + ' From ' +


@TableName + ' WHERE (1>0) and ' + @QueryCondition

75 set @SqlTotalCount = @SqlDistinct + ' @RecordCount=


' + @SqlCountDistinct + ' FROM ' + @TableName + ' WHERE (1>0) and '
+ @ QueryCondition

76 set @SqlStartOrEndID = ' From ' + @TableName +


' WHERE (1>0) and ' + @QueryCondition

77 End

78

79 -- -- Get the total number of query results ---

80 exec sp_executesql @SqlTotalCount , N ' @RecordCount int out '


, @RecordCount out

81

82 declare @TemporaryCount int -- temporary statistics

83 if @RecordCount = 0

84 set @TemporaryCount = 1

85 else

86 set @TemporaryCount = @RecordCount

87
88 -- Get the total number of pages

89 set @PageCount = ( @TemporaryCount + @PageSize - 1 ) /


@PageSize

90

91 /* *The current page is larger than the total number of


pages. The last page is * */

92 if @PageNumber > @PageCount

93 set @PageNumber = @PageCount

94

95 - - /*-----Data paging 2 points processing -------*/

96 declare @pageIndex int -- total / page size

97 declare @lastcount int -- total % page size

98

99 set @pageIndex = @TemporaryCount / @PageSize

100 set @lastcount = @TemporaryCount % @PageSize

101 if @lastcount > 0

102 set @pageIndex = @pageIndex + 1

103 else

104 set @lastcount = @pagesize

105
106 -- //*** Show pagination

107 IF @QueryCondition IS null or @QueryCondition = ''


- is not set display condition

108 the begin

109 IF @pageIndex < 2 or @PageNumber <= @pageIndex /


2 + @pageIndex % 2 -- The first half of the data processing

110 begin

111 if @PageNumber = 1

112 set @SqlTotalCount = @SqlDistinct + '


TOP ' + CAST ( @PageSize as VARCHAR ( 4 )) + ' ' + @FieldList + '
FROM ' + @TableName+ ' ORDER BY ' + @SortFields + ' ' + @SortTypeB

113 else

114 begin

115 if @EnabledSort = 1

116 begin

117 set @SqlTotalCount = @SqlDistinct + '


TOP ' + CAST ( @PageSize as VARCHAR ( 4 )) + ' ' + @FieldList + '
FROM ' + @TableName

118 + ' WHERE ' + @Primarykey + '


<(SELECT MIN( ' + @Primarykey + ' ) FROM ( ' + @SqlDistinct + ' TOP
' + CAST ( @PageSize * ( @PageNumber - 1 ) as Varchar ( 20 )) + ' '
+ @PrimaryKey + ' the FROM ' + @tablename

119 + 'ORDER BY ' + @SortFields + ' '


+ @SortTypeB + ' ) AS TBMinID) ' + ' ORDER BY ' + @SortFields + '
' + @SortTypeB

120 end
121 else

122 begin

123 set @SqlTotalCount = @SqlDistinct + '


TOP ' + CAST ( @PageSize as VARCHAR ( 4 )) + ' '+ @FieldList + '
FROM ' + @TableName

124 + ' WHERE ' + @Primarykey + '


>(SELECT MAX( ' + @Primarykey + ' ) FROM ( ' + @SqlDistinct + ' TOP
' + CAST ( @PageSize * ( @ PageNumber - 1 ) as Varchar ( 20 )) + '
' + @Primarykey +' FROM ' + @TableName

125 + ' ORDER BY ' + @SortFields + ' '


+ @SortTypeB + ' ) AS TBMinID) ' + ' ORDER BY ' + @SortFields + '
' + @SortTypeB

126 end

127 end

128 end

129 else

130 begin

131 set @PageNumber = @pageIndex - @PageNumber + 1


- the second half of the data processing

132 IF @PageNumber <= . 1 - last page data

133 SET @SqlTotalCount = @SqlDistinct + ' *


the FROM ( ' + @SqlDistinct + ' the TOP ' + the CAST ( @lastcount AS
VARCHAR ( . 4 ) ) + ' ' + @FieldList + ' the FROM ' + @tablename

134 + ' the ORDER BY ' + @SortFields + '


' + @SortTypeA + ' ) AS TempTB ' + ' ORDER BY ' + @SortFields + '
' + @SortTypeB

135 else
136 if @EnabledSort = 1

137 begin

138 set @SqlTotalCount = @SqlDistinct + ' *


FROM ( ' + @SqlDistinct + ' TOP ' + CAST ( @PageSize as VARCHAR ( 4
)) + ' ' + @FieldList + ' FROM ' + @TableName

139 + ' WHERE ' + @Primarykey + '


>(SELECT MAX( ' + @Primarykey + ' ) FROM( ' + @SqlDistinct + ' TOP
' + CAST ( @PageSize * ( @PageNumber - 2 ) + @lastcount as Varchar(
20 is )) + ' ' + @PrimaryKey + ' the FROM ' + @tablename

140 + ' the ORDER BY ' + @SortFields +


' ' + @SortTypeA + ' ) the AS TBMaxID) '

141 is + ' the ORDER BY ' + @SortFields


+ ' ' + @SortTypeA + ' ) AS TempTB ' + ' ORDER BY '+ @SortFields +
' ' + @SortTypeB

142 end

143 else

144 begin

145 set @SqlTotalCount = @SqlDistinct + ' *


FROM ( ' + @SqlDistinct + ' TOP ' + CAST ( @PageSize as VARCHAR ( 4
)) + ' ' + @FieldList + ' FROM ' + @TableName

146 + ' WHERE ' +@Primarykey + ' <(SELECT


MIN( ' + @Primarykey + ' ) FROM( ' + @SqlDistinct + ' TOP ' + CAST
( @PageSize * ( @PageNumber - 2 ) + @lastcount as Varchar ( 20 )) +
' ' + @PrimaryKey + ' the FROM ' + @tablename

147 + ' the ORDER BY ' + @SortFields + '


' + @SortTypeA + ' ) AS TBMaxID) '

148 + ' ORDER BY ' + @SortFields + ' '


+ @SortTypeA + ' ) AS TempTB ' + ' ORDER BY ' + @SortFields + ' '
+ @SortTypeB
149 End

150 End

151 End

152

153 the else - there query

154 the begin

155 IF @pageIndex < 2 or @PageNumber <= @pageIndex /


2 + @pageIndex % 2 -- The first half of the data processing

156 begin

157 if @PageNumber = 1

158 set @SqlTotalCount = @SqlDistinct + '


TOP ' + CAST ( @PageSize as VARCHAR ( 4 )) + ' ' + @FieldList + '
FROM ' + @TableName

159 + ' WHERE 1=1 and ' +


@QueryCondition + ' ORDER BY ' + @SortFields + ' ' + @SortTypeB

160 else if ( @EnabledSort = 1 )

161 begin

162 set @SqlTotalCount = @SqlDistinct + '


TOP ' + CAST ( @PageSize as VARCHAR ( 4 )) + ' ' + @FieldList+ '
FROM ' + @TableName

163 + ' WHERE ' + @Primarykey + '


<(SELECT MIN( ' + @Primarykey + ' ) FROM ( ' + @SqlDistinct + ' TOP
' + CAST ( @PageSize * ( @PageNumber - 1 ) as Varchar ( 20 )) + ' '
+ @Primarykey + ' FROM' + @TableName
164 + ' WHERE (1=1) and ' +
@QueryCondition + ' ORDER BY ' + @SortFields + ' ' + @SortTypeB +
' ) AS TBMinID) ' + ' ORDER BY ' + @SortFields + ' ' + @SortTypeB

165 end

166 else

167 begin

168 set @SqlTotalCount = @SqlDistinct + '


TOP' + CAST ( @PageSize as VARCHAR ( 4 )) + ' ' + @FieldList + '
FROM ' + @TableName

169 + ' WHERE ' + @Primarykey + '


>(SELECT MAX( ' + @Primarykey + ' ) FROM ( ' + @SqlDistinct + ' TOP
' + CAST ( @PageSize * ( @PageNumber -. 1 ) AS Varchar ( 20 is )) +
' ' + @PrimaryKey + ' the FROM ' + @tablename

170. + ' the WHERE (=. 1. 1) and ' +


@QueryCondition + ' the ORDER BY ' + @SortFields + ' ' +
@SortTypeB + ' ) AS TBMinID) ' + ' ORDER BY ' + @SortFields + ' ' +
@SortTypeB

171 end

172 end

173 else

174 begin

175 set @PageNumber = @pageIndex - @PageNumber + 1


-- second half of data processing

176 if @PageNumber <= 1 -- last page of data


display

177 set @SqlTotalCount = @SqlDistinct + ' *


FROM ( ' + @SqlDistinct + ' TOP ' + CAST ( @lastcount as VARCHAR (
4 ))+ ' ' + @FieldList + ' FROM ' + @TableName
178 + ' WHERE (1=1) and ' +
@QueryCondition + ' ORDER BY ' + @SortFields + ' ' + @SortTypeA +
' ) AS TempTB ' + ' ORDER BY ' + @SortFields + ' ' + @SortTypeB

179 else if ( @EnabledSort = 1)

180 [ SET @SqlTotalCount = @SqlDistinct + '


* the FROM ( ' + @SqlDistinct + ' the TOP ' + the CAST ( @PageSize
AS VARCHAR ( . 4 )) + ' ' + @FieldList + ' the FROM ' + @tablename

181 + ' the WHERE ' + @Primarykey + '


>(SELECT MAX( ' + @Primarykey + ') The FROM ( ' + @SqlDistinct + '
the TOP ' + the CAST ( @PageSize * ( @PageNumber - 2 ) + @lastcount
AS Varchar ( 20 is )) + ' ' + @PrimaryKey + ' the FROM ' +
@tablename

182 + ' the WHERE ( 1=1) and ' +


@QueryCondition + ' ORDER BY ' + @SortFields + ' ' + @SortTypeA +
' ) AS TBMaxID) ' + ' ORDER BY ' + @SortFields + ' ' + @SortTypeA
+ ' ) AS TempTB ' + ' ORDER BY ' + @SortFields + ' ' + @SortTypeB

183 else

184 set @ SqlTotalCount = @SqlDistinct + ' *


FROM ( ' + @SqlDistinct + ' TOP '+ CAST ( @PageSize as VARCHAR ( 4
)) + ' ' + @FieldList + ' FROM ' + @TableName

185 + ' WHERE ' + @Primarykey + '


<(SELECT MIN( ' + @Primarykey + ' ) FROM( ' + @ SqlDistinct + ' TOP
' + CAST ( @PageSize * ( @PageNumber - 2 )+ @lastcount AS Varchar (
20 is )) + ' ' + @PrimaryKey + ' the FROM ' + @tablename

186 + ' the WHERE (=. 1. 1) and ' +


@QueryCondition + ' the ORDER BY ' + @SortFields + ' ' +
@SortTypeA + ' ) AS TBMaxID) ' + ' ORDER BY ' + @SortFields + ' ' +
@SortTypeA+ ' ) AS TempTB ' + ' ORDER BY ' + @SortFields + ' ' +
@SortTypeB

187 end

188 end

189
190 -- ----Return result-----

191 exec sp_executesql @SqlTotalCount

192 -- SELECT datediff (ms,@timediff,getdate()) as

Time 193 print @SqlTotalCount

194 SET NOCOUNT OFF

The above is the stored procedure, the code is very simple, there are comments, no
explanation.

Third, related entity classes


Because the stored procedure code is called in C# code, in order to facilitate the parameter
passing, I deliberately create an entity class for passing and accepting parameters, such as: total
number of pages and number of records, the name of the class is:
CommonDataResourcePaged. Not much nonsense, directly on the code, the code is as follows:
. 1 /// <Summary>

2 /// generic data source bandit tab

. 3 /// </ Summary>

. 4 public Sealed class CommonDataResourcePaged

. 5 {

. 6 /// <Summary>

. 7 /// table or a plurality of tables to be displayed


Connection

8 /// </summary>

9 public string TableName { get ; set ; }


10

11 /// <summary>

12 /// List of fields to display

13 /// </summary>

14 public stringFieldList { get ; set ; }

15

16 /// <summary>

17 /// Number of records displayed per page

18 /// </summary>

19 public int PageSize { get ; set ; }

20

21 /// < Summary>

22 /// Page number of the record of the page to be displayed

23 /// </summary>

24 public int PageNumber { get ; set ; }

25

26 /// <summary>

27 /// Sort the field list or condition

28 /// </summary>
29 public string SortFields { get ; set ; }

30

31 /// <summary>

32 /// Sort method, 0 is ascending, 1 is descending (if it is


a multi-field arrangement Sort refers to the last a sort order in the
field (without the last sort field ordering flag) - such as a process
parameter passing: 'SortA the Asc, Asc SortB, SortC')

33 is /// </ Summary>

34 is public BOOL EnabledSort { GET ; SET ; }

35

36 /// <Summary>

37 [ /// query without WHERE

38 is /// </ Summary>

39 public StringQueryCondition { get ; set ; }

40

41 /// <summary>

42 /// primary key of the main table

43 /// </summary>

44 public string Primarykey { get ; set ; }

45

46 /// <summary>
47 /// Whether to add the DISTINCT of the query field Default
0 does not add /1 Add

48 /// </summary>

49 public bool EnabledDistinct { get ; set ; }

50

51 /// <summary>

52 ///This field is returned from the database field values,


Output is the field in the database, the total number of pages of the
search result tab

53 is /// </ Summary>

54 is public int the PageCount { GET ; SET ;}

55

56 is /// < Summary>

57 is /// this field is returned to the field values from a


database, the database is Output field, recording the number of
queries to

58 /// </ Summary>

59 public int the RecordCount { GET ; SET ;}

60 }

The above is the code of the entity class, very simple, it will not be explained.
Fourth, Sql Server call code
Here, I only demonstrate how to call this stored procedure in Sql Server, which is very
simple, everyone should know. Ok, that's it, the code is very simple, I want to call the stored
procedure, the call instance is as follows:
1 USE [ Xxxxxxx.Bbbbbb.Dataware ] GO //The name is commented out

3 DECLARE @return_value int , @PageCount int , @RecordCount


int

5 SELECT @PageCount = 0 SELECT @RecordCount = 0

7 EXEC @return_value = [ dbo ] . [ usp_CommonDataResourcePaged ]

@TableName = N ' [literature].[tbl_Literatures] ' ,

8 @FieldList = N '
[ID],[Title],[Authors],[PeriodicalName],[PublicationDate],[VolumeNumbe
r] ' ,

9 @PageSize = 30 ,

10 @PageNumber = 50 ,

11 @SortFields = [ ID ] ,

12 @EnabledSort = N ' 1 ' ,

13 @QueryCondition = N '[ChiefAuthor]= '' ffffff ''' ,

14 @Primarykey = N ' [ID] ' ,

15 @EnabledDistinct = 1 ,

16 @PageCount = @PageCount OUTPUT,

17 @RecordCount = @RecordCount OUTPUT


18

19 SELECT @PageCount as N ' @PageCount ' , @RecordCount as N '


@RecordCount '

20

21 SELECT 'Return Value ' = @return_value

22

23 GO

After the query, you can see the results of the first off, I will not map.

Fifth, the end


I wrote it today, it is time to go to work. By the way, I use IBatis.net in C# code. I need to
make related settings in the configuration file before calling, such as setting the parameters of the
parameters, setting the query result settings and types, etc. It is also very simple to use. , no code
is posted. This is what it is today, and I have time to continue my journey to the MongoDB
series.

Modified SQL paging stored procedure, using the 2-


point method to support sorting
2018-03-04 / VIEWS: 39
/****** Object: StoredProcedure [dbo].[sys_Page_v3] Script Date:
08/13/2014 09:32:28 ******/

SET ANSI_NULLS ON

GO

SET QUOTED_IDENTIFIER ON

GO
-- /*-----Storage process paging processing Sun Wei 2005-03-28 created
-------*/

-- /*-----Storage process paging processing dust 2008-9-1 Modify -----


------*/

-- /*----- 2 points of data processing to make the first half of the


query data the same as the second half of the query -------*/

alter PROCEDURE [dbo].[sys_Page_v3]

@tblName nvarchar ( 200 ), -- -- The connection of the table or


tables to be displayed

@fldName nvarchar ( 500 ) = * , -- -- The list of fields to be


displayed

@pageSize int = 10 , -- -- per The number of records displayed on


the page

@page int = 1 , -- -- The record to display that page

@fldSort nvarchar ( 200 ) = null , -- -- Sort field list or


condition

@Sort bit = 0 , --- Sorting method, 0 is ascending order, 1 is


descending order (if it is a multi-field arrangement Sort refers to
the order of the last sorting field (the last sorting field is not
sorted) - the process is as follows: SortA Asc, SortB Desc , SortC )

@strCondition nvarchar ( 1000 ) = null , -- -- Query condition, no


need where

@ID nvarchar ( 150 ), -- -- Primary key of the main table


@Dist bit = 0 , -- -- Add query Field DISTINCT Default 0 is not
added /1 Add

@pageCount int = 1 output, -- -- Total number of pages after query


results page

@Counts int = 1 output -- -- Number of records queried

AS

SETNOCOUNT ON

Declare @sqlTmp nvarchar ( 1000 ) -- -- Store dynamically generated


SQL statement

Declare @strTmp nvarchar ( 1000 ) -- -- Store the query statement to


get the total number of query results

Declare @strID nvarchar ( 1000 ) -- -- Store Get the query statement


at the beginning or end of the query

Declare @strSortType nvarchar ( 10 ) -- -- Data collation A

Declare @strFSortType nvarchar ( 10 ) -- -- Data collation B

Declare @SqlSelect nvarchar ( 50 ) -- -- SQL construct for queries


containing DISTINCT

Declare @SqlCounts nvarchar ( 50 ) -- -- SQL construct for total


queries containing DISTINCT

Declare @timediff datetime -- time


- consuming test time difference select @timediff = getdate ()

if @Dist = 0

begin

set @SqlSelect = select

set @SqlCounts = Count(*)

end

else

begin

set @SqlSelect = select distinct

set @SqlCounts = Count(DISTINCT +@ID+)

end

if @Sort=0

begin

set @strFSortType= ASC

set @strSortType= DESC

end
else

begin

set @strFSortType= DESC

set @strSortType= ASC

end

- ------ generate queries --------

- here @strTmp to get the number of query results statement

IF @strCondition IS null or @strCondition = - not set display


conditions

the begin

the SET @ sqlTmp = @fldName + the From @tblName

SET @strTmp = @SqlSelect + @Counts = + @SqlCounts + the FROM +


@tblName

SET @strID = the From @tblName

End

the else

the begin
SET @sqlTmp = + @fldName + From @tblName + where
@strCondition

set @strTmp = @SqlSelect+ @Counts=+@SqlCounts+ FROM +@tblName + where


1=1 @strCondition

set @strID = From @tblName + where @strCondition

end

-- -- Get the total number of query results ---

exec sp_executesql @strTmp , N @Counts int out , @Counts out

declare @tmpCounts int

if @Counts = 0

set @tmpCounts = 1

else

set @tmpCounts = @Counts

- obtaining the total number of tabs

SET @pageCount = ( @tmpCounts + @pageSize - . 1 ) / @pageSize

/**//**//**//* *The current page is larger than the total number of


pages. The last page is * */

if @page > @pageCount


set @page = @pageCount

-- / *----- Data page 2 points processing ------- * /

declare @pageIndex int -- total / page size

declare @lastcount int -- total % page size

set @pageIndex = @tmpCounts/@pageSize

set @lastcount = @tmpCounts%@pageSize

if @lastcount > 0

set @pageIndex = @pageIndex + 1

else

set @lastcount = @pagesize

- // Display tab ***

IF @strCondition IS null or @strCondition = - not set display


condition

the begin

IF @pageIndex < 2 or @page <= @pageIndex / 2 + @pageIndex % 2


- the first half of the data processing

Begin
if @page = 1

set @strTmp = @SqlSelect + top + CAST ( @pageSize as VARCHAR ( 6


)) + + @fldName+ from +@tblName

+ order by + @fldSort + + @strFSortType

else

begin

if @Sort=1

begin

set @strTmp=@SqlSelect+ top + CAST(@pageSize as VARCHAR(6))+ +


@fldName+ from +@tblName

+ where +@ID+ <(select min(+ @ID +) from (+ @SqlSelect+ top +


CAST(@pageSize*(@page-1) as Varchar(20)) + + @ID + from +@tblName

+ order by + @ID + + @strFSortType+) AS TBMinID)

+ order by + @fldSort + + @strFSortType

end

else

begin

set @strTmp=@SqlSelect+ top + CAST(@pageSize as VARCHAR(6))+ +


@fldName+ from +@tblName

+ where +@ID+ >(select max(+ @ID +) from (+ @SqlSelect+ top +


CAST(@pageSize*(@page-1) as Varchar(20)) + + @ID + from +@tblName

+ order by + @ID + + @strFSortType+) AS TBMinID)


+ order by + @fldSort + + @strFSortType

end

end

end

else

begin

set @page = @pageIndex-@page+1 --後半部分數據處理

if @page <= 1 - Finally, the data show a

SET @strTmp = @SqlSelect + * from ( + @SqlSelect + Top + the


CAST ( @lastcount AS VARCHAR ( . 6 )) + + @fldName + from +
@tblName

+ Order by + @fldSort + + @strSortType + ) AS TempTB + order


by + @fldSort + + @strFSortType

else

if @Sort=1

begin

set @strTmp=@SqlSelect+ * from (+@SqlSelect+ top + CAST(@pageSize as


VARCHAR(6))+ + @fldName+ from +@tblName

+ where +@ID+ >(select max(+ @ID +) from(+ @SqlSelect+ top +


CAST(@pageSize*(@page-2)+@lastcount as Varchar(20)) + + @ID + from
+@tblName

+ order by + @ID + + @strSortType+) AS TBMaxID)

+ order by + @fldSort + + @strSortType+) AS TempTB+ order by +


@fldSort + + @strFSortType
end

else

begin

set @strTmp=@SqlSelect+ * from (+@SqlSelect+ top + CAST(@pageSize as


VARCHAR(6))+ + @fldName+ from +@tblName

+ where +@ID+ <(select min(+ @ID +) from(+ @SqlSelect+ top +


CAST(@pageSize*(@page-2)+@lastcount as Varchar(20)) + + @ID + from
+@tblName

+ order by + @ID + + @strSortType+) AS TBMaxID)

+ order by + @fldSort + + @strSortType+) AS TempTB+ order by +


@fldSort + + @strFSortType

than

than

than

Else -- there is a query condition

begin

if @pageIndex < 2 or @page <= @pageIndex / 2 + @pageIndex % 2


-- the first half of the data processing

begin

if @page = 1

set @strTmp = @SqlSelect + top + CAST ( @ the pageSize AS


VARCHAR ( . 6 )) + + @fldName + from + @tblName
+ WHERE . 1 = . 1 @strCondition + order by + @fldSort + +
@strFSortType

else if(@Sort=1)

begin

set @strTmp=@SqlSelect+ top + CAST(@pageSize as VARCHAR(6))+ +


@fldName+ from +@tblName

+ where +@ID+ <(select min(+ @ID +) from (+ @SqlSelect+ top +


CAST(@pageSize*(@page-1) as Varchar(20)) + + @ID + from +@tblName

+ where 1=1 @strCondition + order by + @ID + + @strFSortType+) AS


TBMinID)

+ + @strCondition + order by + @fldSort + + @strFSortType

end

else

begin

set @strTmp=@SqlSelect+ top + CAST(@pageSize as VARCHAR(6))+ +


@fldName+ from +@tblName

+ where +@ID+ >(select max(+ @ID +) from (+ @SqlSelect+ top +


CAST(@pageSize*(@page-1) as Varchar(20)) + + @ID + from +@tblName

+ where 1=1 @strCondition + order by + @ID + + @strFSortType+) AS


TBMinID)

+ + @strCondition + order by + @fldSort + + @strFSortType

end

end

else
begin

Set @page = @pageIndex - @page + 1 -- second half of data


processing

if @page <= 1 -- last page data display

set @strTmp = @SqlSelect + * from ( + @SqlSelect + top + CAST (


@lastcount AS VARCHAR ( . 6 )) + + @fldName + from + @tblName

+ WHERE . 1 = . 1 + @strCondition + order by + @fldSort + +


@strSortType+) AS TempTB+ order by + @fldSort + + @strFSortType

else if(@Sort=1)

set @strTmp=@SqlSelect+ * from (+@SqlSelect+ top + CAST(@pageSize as


VARCHAR(6))+ + @fldName+ from +@tblName

+ where +@ID+ >(select max(+ @ID +) from(+ @SqlSelect+ top +


CAST(@pageSize*(@page-2)+@lastcount as Varchar(20)) + + @ID + from
+@tblName

+ where 1=1 + @strCondition + order by + @ID + + @strSortType+) AS


TBMaxID)

+ + @strCondition+ order by + @fldSort + + @strSortType+) AS TempTB+


order by + @fldSort + + @strFSortType

else

set @strTmp=@SqlSelect+ * from (+@SqlSelect+ top + CAST(@pageSize as


VARCHAR(6))+ + @fldName+ from +@tblName

+ where +@ID+ <(select min(+ @ID +) from(+ @SqlSelect+ top +


CAST(@pageSize*(@page-2)+@lastcount as Varchar(20)) + + @ID + from
+@tblName

+ where 1=1 + @strCondition + order by + @ID + + @strSortType+) AS


TBMaxID)
+ + @strCondition+ order by + @fldSort + + @strSortType+) AS TempTB+
order by + @fldSort + + @strFSortType

end

end

-- ----Return the query result -----

exec sp_executesql @strTmp

-- select datediff(ms,@timediff,getdate()) as Time -consuming

-- print @strTmp

SET NOCOUNT OFF

HOME

SQL job and schedule creation


2018-01-11 / VIEWS: 31

Transfer from: http://www.cnblogs.com/accumulater/p/6223909.html


- the definition to create a job transferred from
http://hi.baidu.com/procedure/blog/item/7f959fb10d76f95d092302dd.html

the DECLARE @jobid UNIQUEIDENTIFIER

EXEC msdb.dbo.sp_add_job

@job_name = N ' job name ' ,

@job_id = @jobid the OUTPUT


- Define the job step

DECLARE @sql nvarchar ( 400 ), @dbname sysname

SELECT @dbname = DB_NAME (), -- the job step executes

@sql = N ' in the current database -- the job step content '
-- the general definition is Jobs processed using TSQL, here define
the Transact-SQL statement to be executed

EXEC msdb.dbo.sp_add_jobstep

@job_id = @jobid ,

@step_name = N ' job step name ' ,

@subsystem = ' TSQL ' , --The type of step, generally TSQL

@database_name = @dbname ,

@command = @sql

- Create a schedule (using several job scheduling templates


specifically defined later)

EXEC msdb..sp_add_jobschedule

@job_id = @jobid ,

@name = N ' scheduling name ' ,

@freq_type = 4 , -- every day

@freq_interval = 1 , - - Specify how many days to


occur, here is 1 day.
@freq_subday_type = 0x8 , -- Repeat mode, 0x1 = At the
specified time, 0x4 = how many minutes, 0x8 = how many hours to
execute

@freq_subday_interval = 1 , -- Repeat cycle Number, here


is executed every hour

@active_start_date = NULL , -- the start date of the job


execution, the current date is NULL, the format is YYYYMMDD

@active_end_date = 99991231 , -- the stop date of the job


execution, the default is 99991231, the format is YYYYMMDD

@active_start_time = 00000 , -- the job is executed Start


time, format HHMMSS

@active_end_time = 235959 - stop time for job execution


in HHMMSS format

- add the target server

the DECLARE @ servername Sysname

the SET @ servername = the CONVERT ( nvarchar ( 128 ), the


SERVERPROPERTY (N ' ServerName ' ))

EXEC msdb.dbo.sp_add_jobserver

@job_id = @jobid ,

@server_name = @ servername - using the current SQL


Instance

-- Scheduling template definition


-- / * - Daily scheduling

EXEC msdb..sp_add_jobschedule

@job_id = @jobid ,

@name = N ' scheduling name ' ,

@freq_type = 4 , -- every day

@freq_interval = 1 , -- specify each How many days


occur, here is 1 day.

@freq_subday_type = 0x8 , -- repeat mode, 0x1 = at the


specified time, 0x4 = how many minutes, 0x8 = how many hours to
execute

@freq_subday_interval = 1 , -- repeat cycle number, here


Executed once an hour

@active_start_date = NULL , -- the start date of the job


execution, the current date is NULL, the format is YYYYMMDD

@active_end_date = 99991231 , -- the stop date of the job


execution, the default is 99991231, the format is YYYYMMDD

@active_start_time = 00000 , -- The start time of the job


execution, in the format HHMMSS

@active_end_time = 235959 - the stop time of the job


execution, in the format HHMMSS

-- */

-- / *-- Weekly schedule

EXEC msdb.dbo.sp_add_jobschedule
@job_id = @jobid ,

@name = N ' scheduling name ' ,

@freq_type = 8 , -- weekly

@freq_recurrence_factor = 1 , -- every few weeks to execute


, here is

@freq_interval = 62 per week , -- executed on the


day of the week, represented by POWER(2,N), the value of N is 0~6,
representing Sunday~Saturday, if two are specified, the values are
added. For example, a value of 65 means execution on Sunday and Sunday
(POWER(2,0)+POWER(2,6))

@freq_subday_type = 0x8 , --Repeat mode, 0x1=At the


specified time, 0x4=How many minutes, 0x8=How many hours to execute

@freq_subday_interval = 1 , -- Repeat the number of


cycles, here every hour

@active_start_date = NULL , -- the start date of the job


execution, When NULL, the current date is represented, the format is
YYYYMMDD

@active_end_date = 99991231 , -- the stop date of the job


execution, the default is 99991231, the format is YYYYMMDD

@active_start_time = 00000 , -- the start time of the job


execution, the format is HHMMSS

@active_end_time = 235959 -- The stop time of the job


execution, in the format HHMMSS

-- */

- / * - month schedule (every X number of monthly several months)

EXEC msdb.dbo.sp_add_jobschedule
@job_id = @jobid ,

the @name = N ' schedule name ' ,

@freq_type = 16 , - per month

@ Freq_recurrence_factor = 2 , -- every few months, here


every 2 months

@freq_interval = 2 , -- executed on the first few


days of the execution month, here is the second day

@freq_subday_type = 0x8 , -- repeat mode, 0x1 = at the


specified time, 0x4 = how many minutes, 0x8 = how many hours to
execute

@freq_subday_interval = 1 , -- the number of repetition


cycles, where

@active_start_date = NULL is executed every hour , -- the


start date of the job execution, the current date is NULL, the format
is YYYYMMDD

@active_end_date = 99991231 , -- the stop date of the job


execution, default Think 99991231, the format is YYYYMMDD

@active_start_time = 00000 , -- the start time of the job


execution, the format is HHMMSS

@active_end_time = 235959 -- the stop time of the job


execution, the format is HHMMSS

-- */

- / * - month schedule (relative time every X months)

EXEC msdb.dbo.sp_add_jobschedule

@job_id = @jobid ,
the @name = N ' schedule name ' ,

@freq_type = 32 , - monthly

@freq_recurrence_factor = 2 , -- Execute every few months,


here every 2 months

@freq_interval = 9 , -- Execute at that time of


the month, 1~7=Sunday to Saturday, 8=Day, 9=Workday, 10=Weekend

@freq_relative_interval = 1 , -- executed at the first


relative time, the allowed values are 1, 2, 4, 8 for the first to
fourth relative time, and 16 for the last relative time

@freq_subday_type = 0x8 , -- repeat mode, 0x1 = at the


specified time, 0x4 = how many minutes, 0x8 = how many hours to
execute

@freq_subday_interval = 1 , -- repeat cycle number, here


every hour

@active_start_date = NULL , - - the start date of the job


execution, when NULL, the current date, the format is YYYYMMDD

@active_end_date = 99991231 , -- the stop date of the job


execution, the default is 99991231, the format is YYYYMMDD

@active_start_time = 00000 , -- the start time of the job


execution, The format is HHMMSS

@active_end_time = 235959 -- the stop time of the job


execution, in the format HHMMSS

-- */

-- / *-- Job scheduling

EXEC executed at a specific time msdb.dbo.sp_add_jobschedule


@job_id = @jobid ,

@name = N ' scheduling name ' ,

@freq_type = 64 -- 64=Running when the SQLServerAgent


service starts, 128 = Run when the computer is idle

-- * /

- / * - only performed once a job scheduler

EXEC msdb..sp_add_jobschedule

@job_id = @jobid ,

the @name = N ' schedule name ' ,

@freq_type = . 1 , - only once

@active_start_date = NULL , - operations The start date


of execution, when NULL, indicates the current date, the format is
YYYYMMDD

@active_start_time = 00000 -- the start time of the job


execution, in the format HHMMSS

-- */
A generic stored procedure written by yourself:

set ANSI_NULLS ON

set QUOTED_IDENTIFIER ON

go

The ALTER proc [ the dbo ] . [ Formula_CreateJob ]

@jobname VARCHAR ( 100 ), - job name

@sql VARCHAR ( 8000 ), - the command to be


executed, - the contents of the job step, use is generally defined
TSQL jobs processed, Transact-SQL statements to execute defined here

- @ servername Sysname = '', the --job Server name

- @dbname Sysname = '', - defaults to the current database name

@freqtype the INT = 4 , - the frequency 4 Day, 8 weeks, 16


months of scheduling (monthly number per X months, 32 months
scheduling (relative time per X months)
---------------------------------------------------- ---------------
----------

@freqInterval INT = 1 ,

- specify the number of days happen every time, here is one day.

- in the days of the week Execution, represented by POWER(2,N), the


value of N is 0~6, representing Sunday~Saturday. If two are specified,
the values are added. For example, a value of 65 means execution on
Sunday and Sunday (POWER(2) , 0) + POWER (2, 6))

-- Execute on the first day of the execution

month , here is the first day - at the time of the month, 1~7 =
Sunday to Saturday, 8 = day, 9 = Workday, 10=weekend

@freq_recurrenceFactor INT = 1 , -- every few months (weeks),


every 1

@freq_relativeInterval INT = 1 , -- executed in the first relative


time, the allowed value is 1, 2 4,8 represents the first to fourth
relative time, and 16 represents the last relative time.

-- Daily frequency

@freqSubdayType INT = 1 , -- Repeat mode, 0x1 = At the


specified time, 0x4 = how many minutes, 0x8 = how many hours to
execute

@freqSubdayInterval INT = 1 , -- Repeat cycle number, for


example freqSubdayType is 8, freqSubdayInterval is 2, then every 2
hours

- duration

@active_startDate NVARCHAR ( 20 ) = NULL , -- the start date of


the job execution, when NULL, the current date, in the format YYYYMMDD
@active_endDate NVARCHAR ( 20 ) = ' 99991231 ' , -- the stop date
of the job execution, the default is 99991231, the format is YYYYMMDD

@active_startTime NVARCHAR ( 20 ) = ' 0 ' , -- the start time of


the job execution, in the format HHMMSS

@active_endTime NVARCHAR ( 20 ) = ' 235959 ' -- the stop time


of the job execution, in the format HHMMSS

AS

BEGIN

--定義創建作業

DECLARE @jobid uniqueidentifier

EXEC msdb.dbo.sp_add_job

@job_name = @jobname,

@job_id = @jobid OUTPUT

- the definition of the job step

the DECLARE @dbname Sysname

the SELECT @dbname = the DB_NAME () - job step executed in the


current database

EXEC msdb.dbo.sp_add_jobstep

@job_id = @jobid ,
@step_name = N ' performed formula job, generating cost
breakdown ' ,

@subsystem = ' TSQL ' , -- the type of the step, generally


TSQL

@database_name = @dbname ,

@command = @sql

- Create schedules (using several job scheduling templates


specifically defined later)

-- @freqtype INT=4, -- Frequency 4 days, 8 weeks, 16 months schedule


(monthly number per X months, 32 months schedule) (relative time per X
months)

IF @freqtype = 4

BEGIN

EXEC msdb.dbo.sp_add_jobschedule

@job_id = @jobid ,

@name = N ' day schedule, generate cost details ' ,

@freq_type = @freqtype , -- every day

@ freq_interval = @freqInterval , - specify the


number of days happen every time, here is one day.

@freq_subday_type = @freqSubdayType , -- Repeat mode,


0x1 = at the specified time, 0x4 = how many minutes, 0x8 = how many
hours to execute
@freq_subday_interval = @freqSubdayInterval , -- repeat
cycle number, here every hour

@active_start_date = @active_startDate , -- job execution


The start date, when NULL, indicates the current date, the format is
YYYYMMDD

@active_end_date = @active_endDate , -- the stop date of the


job execution, the default is 99991231, the format is YYYYMMDD

@active_start_time = @active_startTime , -- the start time


of the job execution, format HHMMSS

@active_end_time = @active_endTime -- the stop time of


the job execution, in the format HHMMSS

END

IF @freqtype = 8

BEGIN

EXEC msdb.dbo.sp_add_jobschedule

@job_id = @jobid ,

@name = N ' weekly schedule, generate cost details ' ,

@freq_type = @freqtype , -- weekly

@freq_recurrence_factor = @freq_recurrenceFactor , -- every


few weeks to execute, here Is weekly

@freq_interval = @freqInterval , -- executed on


the day of the week, represented by POWER(2,N), the value of N is 0~6,
which represents Sunday~Saturday, if two are specified, the values are
added, for example A value of 65 indicates execution on Sunday and
Sunday (POWER(2,0)+POWER(2,6))

@freq_subday_type = @freqSubdayType , --Repeat mode,


0x1=At the specified time, 0x4=How many minutes, 0x8=How many hours to
execute

@freq_subday_interval = @freqSubdayInterval , -- Repeat


the number of cycles, here every hour

@active_start_date = @active_startDate , -- Start of job


execution Date, when NULL, indicates the current date, the format is
YYYYMMDD

@active_end_date = @active_endDate , -- the stop date of the


job execution, the default is 99991231, the format is YYYYMMDD

@active_start_time = @active_startTime , -- the start time


of the job execution, the format is HHMMSS

@active_end_time = @active_endTime -- The stop time of


the job execution, in the format HHMMSS

END

IF @freqtype = 16

BEGIN

EXEC msdb.dbo.sp_add_jobschedule

@job_id = @jobid ,

@name = N ' monthly schedule, generate cost breakdown ' ,

@freq_type = @freqtype , - per month

@freq_recurrence_factor = @freq_recurrenceFactor , - once, how


many here every week Is weekly
@freq_interval = @freqInterval , -- specifies how
many days to occur, here is 1 day.

@freq_subday_type = @freqSubdayType , -- repeat mode,


0x1 = at the specified time, 0x4 = how many minutes, 0x8 = how many
hours Execute

@freq_subday_interval once= @freqSubdayInterval , -- the


number of repetition cycles, where

@active_start_date = @active_startDate is executed every


hour , -- the start date of the job execution, the current date is
NULL, the format is YYYYMMDD

@active_end_date = @active_endDate , -- the job is executed


Stop date, default is 99991231, format is YYYYMMDD

@active_start_time = @active_startTime , -- start time of


job execution, format is HHMMSS

@active_end_time = @active_endTime -- stop time of job


execution, format is HHMMSS

END

IF @freqtype = 32

BEGIN

EXEC msdb.dbo.sp_add_jobschedule

@job_id = @jobid ,

@name = N ' monthly schedule, generate cost breakdown ' ,

@freq_type = @freqtype , - per month

@freq_recurrence_factor = @freq_recurrenceFactor , - each


perform a number of weeks, here is the weekly
@freq_interval = @freqInterval , -- specifies how
many days to occur, here is 1 day.

@freq_relative_interval = @freq_relativeInterval , --
executed at the first relative time, the allowed values are 1, 2, 4, 8
represents the 1~4 relative time , 16 indicates the last relative time

@freq_subday_type = @freqSubdayType , --Repeat mode,


0x1=At the specified time, 0x4=How many minutes, 0x8=How many hours to
execute

@freq_subday_interval = @freqSubdayInterval , -- Repeat


the number of cycles, here every hour

@active_start_date = @active_startDate , -- Start of job


execution Date, when NULL, indicates the current date, the format is
YYYYMMDD

@active_end_date = @active_endDate , -- the stop date of the


job execution, the default is 99991231, the format is YYYYMMDD

@active_start_time = @active_startTime , -- the start time


of the job execution, the format is HHMMSS

@active_end_time = @active_endTime -- The stop time for


the job execution, in the format HHMMSS

END

- add the target server


the DECLARE @ servername Sysname

the SET @ servername = the CONVERT ( nvarchar ( 128 ), the


SERVERPROPERTY (N ' ServerName ' ))

EXEC msdb.dbo.sp_add_jobserver

@job_id = @jobid ,

@server_name = @ servername - using the current SQL


Instance

END

Vous aimerez peut-être aussi