-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdbo.SVF_GetMonthlyPartitionNo.UserDefinedFunction.sql
100 lines (95 loc) · 1.4 KB
/
dbo.SVF_GetMonthlyPartitionNo.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
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_GetMonthlyPartitionNo]
(
@TableName varchar(128)
, @MonthDate date = null
)
/*
select dbo.SVF_GetMonthlyPartitionNo('Test_Monthly', '2026-01-01')
*/
RETURNS int
AS
BEGIN
if @MonthDate is null
begin
set @MonthDate = GETDATE()
end
declare @ int = -1
;with TPartitions
as
(
select
a.LeftValue
, a.RightValue
, @MonthDate 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 <= @MonthDate
)
and
(
(
a.LeftValue is not null
and
a.RightValue is null
and
not exists
(
select
1
from
TPartitions aa
where
aa.LeftValue > a.LeftValue
)
)
or
a.RightValue > @MonthDate
)
)
select
@ = a.[PartitionNumber]
from
T a
return @
END
GO