-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdbo.SVF_GetMonthlyExclusivePartitionNo.UserDefinedFunction.sql
124 lines (119 loc) · 1.84 KB
/
dbo.SVF_GetMonthlyExclusivePartitionNo.UserDefinedFunction.sql
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
USE [MonthlyPartitionsTest]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: <Author,,Name>
-- Create date: <Create Date, ,>
-- Description: <Description, ,>
-- =============================================
CREATE FUNCTION [dbo].[SVF_GetMonthlyExclusivePartitionNo]
(
@TableName varchar(128)
, @Date date = null
)
/*
--获取日期所在按月独占分区编号 (-1: 该日期无该月独占分区, 0: 该日期已滚动过期, N: 该日期的独占按月分区编号)
select dbo.[SVF_GetMonthlyExclusivePartitionNo]('Test_Monthly', '2010-01-01')
*/
RETURNS int
AS
BEGIN
if @Date is null
begin
set @Date = GETDATE()
end
declare @ int = -1
;with TPartitions
as
(
select
a.*
from
iTVF_TablesPartitionsStorageInfo
(
@TableName
) a
)
select
@ = 0
where
(
select
min(aa.BoundaryValue)
from
TPartitions aa
) > @Date
if (@ < 0)
begin
;with TPartitions
as
(
select
a.LeftValue
, a.RightValue
, @Date as MonthDate
, a.[PartitionNumber]
, a.FileGroupName
from
iTVF_TablesPartitionsStorageInfo
(
@TableName
) a
)
, T
as
(
select
*
from
TPartitions a
where
(
(
a.LeftValue = a.RightValue
and
not exists
(
select
1
from
TPartitions aa
where
aa.LeftValue < a.LeftValue
)
)
or
a.LeftValue <= @Date
)
and
(
(
a.LeftValue is not null
and
a.RightValue is not null
and
not exists
(
select
1
from
TPartitions aa
where
aa.LeftValue > a.LeftValue
)
)
or
a.RightValue > @Date
)
)
select
@ = a.[PartitionNumber]
from
T a
end
return @
END
GO