Blog Pages

Execute as specific user

WITH EXECUTE AS 'User1'

Execute an object as specific user - in functions (except inline table-valued functions), procedures, queues, and triggers.

Example:
-- login with dbo

CREATE PROCEDURE dbo.ExecuteAs_Demo
WITH EXECUTE AS 'Lms'
AS
SELECT user_name()
EXECUTE AS CALLER;
SELECT user_name(); -- Shows execution context is set to SqlUser2, the caller of the module.
REVERT;
SELECT user_name(); -- Shows execution context is set to SqlUser1.
GO

SELECT user_name() --result: dbo
exec  dbo.ExecuteAs_Demo --result: Lms, dbo, Lms

No comments:

Post a Comment