
Implicit Context Switching
The execution context of a module, such as a stored procedure, trigger, queue, or user-defined function, can be implicitly changed by specifying a user or login name in an EXECUTE AS clause in the module definition.
By specifying the context in which the module is executed, you can control which user account SQL Server uses to validate permissions on any objects referenced by the module. This provides additional flexibility and control in managing permissions across the object chain that exists between user-defined modules and the objects referenced by those modules. Permissions can be granted to users on the module itself, without having to grant explicit permissions on the referenced objects. Only the user that the module is impersonating needs to have permissions on the objects accessed by the module.
The level of impersonation is determined by the type of module in which the impersonation is defined.
Server-level impersonation can be defined in the following:
The scope of server-level impersonation is the same as that previously defined in "Explicit Server-Level Context Switching."
Database-level impersonation can be defined in the following:
-
DML triggers
-
Queues
-
Stored procedures
-
User-defined functions
-
The scope of database-level impersonation is the same as that previously defined in "Explicit Database-Level Context Switching."
-
For more information about implicit context switching, see Using EXECUTE AS in Modules.
Example
In the following example, Mary is the owner of the table MyTable. She wants user Scott to be able to truncate the table, but Scott has no direct permissions on the table. So, she creates the stored procedure dbo.usp_TruncateMyTable and grants EXECUTE permissions on the procedure to Scott. When Scott executes the stored procedure, the Database Engine verifies the permissions to truncate the table as if Mary herself were executing the stored procedure. Because she is the table owner, the statement succeeds even though Scott has no direct permissions on the table itself.
CREATE PROCEDURE dbo.usp_TruncateMyTable
WITH EXECUTE AS SELF
AS TRUNCATE TABLE MyDB..MyTable;