Context Switching or Database Impersonation using EXEC AS
— Switching execution context to DBUser, to test the procedure
EXECUTE dbo.LogError’Primary Key violation.’
— Reverting back the execution context
If the database user calls the procedure again or on subsequent execution, since this log table already exists it will log the information in the table and will complete the execution of the procedure and so does not impersonate the database owner as it does not require additional privileges.
Finally, the below script cleans up the objects created in this session.
— Clean up scripts
— Remove the created procedure and table
— Remove the temporary principals.
I this article, I briefly discussed the SETUSER command (which was the only option prior to SQL Server 2000) to impersonate the database user, its limitations and how EXEC or EXECUTE AS clause overcomes these limitations. The new EXEC AS clause allows you to change the execution/security context of a session by explicitly specifying a login or user name in an EXECUTE AS statement or implicitly by specifying the EXECUTE AS clause in a module definition. You can use the REVERT statement to switch back the execution context to the caller of the last EXECUTE AS clause.