Assuming I have a table like this one:
CREATE TABLE user_delegates (
[id] INT IDENTITY(1,1) NOT NULL,
[user_from] VARCHAR(10) NOT NULL,
[user_to] VARCHAR(10) NOT NULL,
CONSTRAINT [PK_user_delegates] PRIMARY KEY CLUSTERED ([id] ASC),
CONSTRAINT [UK_user_delegates] UNIQUE ([user_from] ASC)
)
So an user A has to right to delegate her system access to another user B. When she does that, she won’t be able to access the system anymore – user B will have to “break” that delegation before she is able to use the system again…
BUT also consider that, if user B delegates access to user C, user C will also start impersonating user A, and so on.
(I know this seems to be a security nightmare – please let’s just forget about that, OK? :-))
Also consider those records:
INSERT INTO user_delegates([user_from], [user_to]) values ('ANTHONY', 'JOHN')
INSERT INTO user_delegates([user_from], [user_to]) values ('JOHN', 'JOHN')
INSERT INTO user_delegates([user_from], [user_to]) values ('KARL', 'JOSHUA')
INSERT INTO user_delegates([user_from], [user_to]) values ('JOSHUA', 'PIOTR')
INSERT INTO user_delegates([user_from], [user_to]) values ('PIOTR', 'HANS')
So what I need is finding the last (which means the active) delegation for each user.
I have come to a solution that I’ve decided to not show here (unless everybody ignores me, which is always a possibility). All I can say is that it is a somewhat long answer, and it surely seems like using a cannon to kill a flea…
But how would you do that? Consider any relevant SQL Server extension available, and notice we’re looking for an answer that is both elegant and with a good performance…
BTW, this is the expected result set:
id user_from user_to
----------- ---------- ----------
1 ANTHONY JOHN
2 JOHN JOHN
3 KARL HANS
4 JOSHUA HANS
5 PIOTR HANS
(5 row(s) affected)
And thanks in advance!
1 Answer