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

Is there a T-sql command, like the Oracle "Connect" which lets me change the user that I am logged in as?

share|improve this question
up vote 5 down vote accepted

You can use the EXECUTE AS command:

share|improve this answer
Just what I was looking for - thank you! – Daniel Williams Aug 16 '12 at 3:46
Future users: Be really careful using EXECUTE AS on a connection from a connection pool (ie: any SqlConnection in .NET): it automatically resets the connection to prevent security leaks, which will break all the rest of the active connections from that pool. Furthermore, this will only happen sporadically when you're in a threaded environment, so you might not figure it out for months. Not that I know anyone who that happened to... – Crisfole Nov 19 '14 at 15:50
If you want to bust the pooling you can add "Pooling=false" to your connection string in .NET (Pooling in the SqlConnectionStringBuilder). I recognize that these tips aren't 100% DBA specific, but they might bite users reading this. – Crisfole Nov 19 '14 at 15:52

You can try SetUser 'username' too. To revert just run SetUser. Verify by running select suser_name()

share|improve this answer
select suser_name() appears to show the login in use for me rather than the user name. Think the the call for getting user name is select DB_Name(). +1 because I didnt know how to do this either though! – Jonny Leeds Mar 27 '14 at 14:00

Using sqlcmd.exe or Management Studio in SQLCMD mode, you can use the :connect macro to change the connection in the middle of a script. (See here for the full syntax -- weirdly, I can't find documentation for this on MSDN.)

If you just need to test something as a different principal, you can use EXECUTE AS to impersonate the principal, and REVERT to back out.

share|improve this answer

The question has multiple answers, dependent on the context of 'changing the user that I am logged in as.'

A public website will have one or a few 'user accounts' which are used by every site visitor. Even through those accounts, it may be necessary to elevate a permission to execute, for instance, dynamic SQL in solving a multivariable search requirement.

Errand Sommarskog has a very detailed discussion on the security and management of user accounts via T-SQL in stored procedures.

share|improve this answer

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.