Context Switching or Database Impersonation using EXEC AS
On the first execution, the table would not exist so the
procedure will impersonate the database owner (shown in the image below) and create
the table, assign INSERT and SELECT permissions and then revert back the
execution context to original caller.
— Switching execution context to DBUser, to test the procedure
— Reverting back the execution context
If the database
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.
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.