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. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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
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:

EXEC AS USER = 'SomeUser';
EXEC AS USER = 'SomeUser1';
EXEC AS USER = 'SomeUser2';
share|improve this answer

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 '14 at 14:39

Your Answer


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.