Take the 2-minute tour ×
Database Administrators Stack Exchange is a question and answer site for database professionals who wish to improve their database skills and learn from others in the community. It's 100% free, no registration required.

When there are nested impersonations (as in exec as user = 'user1'; exec as user = 'user2'; exec as user = 'user1';), is there a way to revert all of them without having to use the revert command multiple times (e.g. revert all;)?

Or at least, if one must use revert repeatedly, is there a way to check if there is an active impersonation so one could loop the command as many times as needed (e.g. while @@IMPERSONATION_COUNT > 0 revert;)?

share|improve this question
add comment

2 Answers

up vote 1 down vote accepted

You could capture the name of the current user at the start of your batch, then compare that to the then-current user at the point where you want to REVERT back to the original user.

For instance:

DECLARE @Name SYSNAME;
SET @Name = SUSER_NAME();
SELECT @Name;
EXEC AS USER = 'SomeUser';
EXEC AS USER = 'SomeUser1';
EXEC AS USER = 'SomeUser2';
SELECT SUSER_NAME();
WHILE @Name <> SUSER_NAME() REVERT;
SELECT SUSER_NAME();
share|improve this answer
add comment

You could assign the current context to a cookie then revert to that cookie when you desire to.

share|improve this answer
    
Didn't know about that, thanks! However, I don't like the idea of being stuck in an impersonation if I lose the cookie value for any reason. Seems like this feature is more useful to prevent revert than to allow reverting as many times as needed. –  Dang Apr 2 at 14:39
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.