Wednesday, October 03, 2007

Whodunnit?

If your code is running in a Sql Server context (sproc, trigger, CLR assembly, etc.) and you wish to know who initiated the execution, you can try the T-SQL command SELECT SYSTEM_USER.  This will give you one of three answers:

  1. The Sql Server userid, if Sql Server Authentication was used to log in
  2. The Windows user in the form Domain\UserLoginName, if Windows Authentication was used to log in
  3. The name of the currently executing context

Number three is interesting, because it masks the "real" user identifier behind a persona.  To change your context, issue the command

EXECUTE AS USER = 'Gsl\SierraServer'

Then no matter who you are or how you logged in to the server, SELECT SYSTEM_USER will return "Gsl\SierraServer".  The BOL even calls it the "impersonated" context.

Not that customers would ever fiddle with sprocs or table schema or permissions that you carefully craft and install...

No comments: