-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathGetParentID.sql
40 lines (35 loc) · 1.77 KB
/
GetParentID.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
--------------------------------------------------------------------------------------------------------------------------------
-- GET PARENT ID (FUNCTION)
--------------------------------------------------------------------------------------------------------------------------------
-- Given a @TopicID, returns the TopicID of the node above it in the Topics nested set hierarchy.
--------------------------------------------------------------------------------------------------------------------------------
CREATE
FUNCTION [dbo].[GetParentID] (
@TopicID INT
)
RETURNS INT
AS
BEGIN
------------------------------------------------------------------------------------------------------------------------------
-- DECLARE AND DEFINE VARIABLES
------------------------------------------------------------------------------------------------------------------------------
DECLARE @CurrentParentID INT
------------------------------------------------------------------------------------------------------------------------------
-- GET PARENT ID FROM HIERARCHY
------------------------------------------------------------------------------------------------------------------------------
SELECT @CurrentParentID = (
SELECT TOP 1
TopicID
FROM Topics t2
WHERE t2.RangeLeft < t1.RangeLeft
AND t2.RangeRight > t1.RangeRight
ORDER BY t2.RangeRight-t1.RangeRight ASC
)
FROM Topics t1
WHERE TopicID = @TopicID
ORDER BY RangeRight-RangeLeft DESC
------------------------------------------------------------------------------------------------------------------------------
-- RETURN VALUE
------------------------------------------------------------------------------------------------------------------------------
RETURN @CurrentParentID
END