-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathGetParentID.sql
More file actions
26 lines (26 loc) · 968 Bytes
/
GetParentID.sql
File metadata and controls
26 lines (26 loc) · 968 Bytes
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
--------------------------------------------------------------------------------------------------------------------------------
-- 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 @CurrentParentID INT
SELECT @CurrentParentID = (
SELECT TOP 1
TopicID
FROM Topics t2
WHERE t2.RangeLeft < t1.RangeLeft
AND ISNULL(t2.RangeRight, 0) > ISNULL(t1.RangeRight, 0)
ORDER BY t2.RangeRight-t1.RangeRight ASC
)
FROM Topics t1
WHERE TopicID = @TopicID
ORDER BY RangeRight-RangeLeft DESC
RETURN @CurrentParentID
END