I want to get last reference Id from same table. I have following table.
ID UserId DelegatedToUserId
1 100 101
2 101 102
3 102 103
4 103 NULL
5 104 109
I just can't get my head around. I know what I want, just simply can't get it out on the screen. So when I ask for 100 query should return 103, when I ask 101 or 102 again it should return 103. when user enters 104 it should return 109
And when I ask for 103 it should return 103 as there is no delegate for this.
can this be done in single sql query ?
Personally, I would go with this:
DECLARE @UserID int = 103;
WITH VTE AS
(SELECT *
FROM (VALUES (1, 100, 101),
(2, 101, 102),
(3, 102, 103),
(4, 103, NULL),
(5, 104, 109)) AS V (ID, UserID, DelegatedToUserID) ),
rCTE AS
(SELECT V.ID,
V.UserID,
V.DelegatedToUserID
FROM VTE V
WHERE UserID = @UserID
UNION ALL
SELECT V.ID,
V.UserID,
V.DelegatedToUserID
FROM rCTE r
JOIN VTE V ON r.DelegatedToUserID = V.UserID)
SELECT *
FROM rCTE
WHERE rCTE.DelegatedToUserID IS NULL;
As I mentioned in the comments, however, passing 104
will return no rows as user 109
does not exist in the table.