SQL Server Does REVERT work when stored procedure is executed from another user?

mtb9vblg  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(100)

I have these two stored procedures, and Sales.spExec1 calls dbo.spExec2 .

When I try to REVERT in the 2nd stored procedure, it doesn't go back to original_login() .

Does this mean that REVERT works within a stored procedure? It does revert when I call it in Sales.spExec1 .

CREATE PROCEDURE Sales.spExec1 
AS
BEGIN
    PRINT SUSER_SNAME()  -- 'MyDomain\Bob.Smith'
    PRINT original_login() -- 'MyDomain\Bob.Smith'

    EXECUTE AS USER = 'TempUser';
    EXEC dbo.spExec2

    REVERT;

    /* REVERT works in SP where initial EXECUTE AS USER ran */
    print SUSER_SNAME()  -- 'MyDomain\Bob.Smith'
    print original_login() -- 'MyDomain\Bob.Smith'
END;
GO

CREATE PROCEDURE dbo.spExec2
AS
BEGIN
    PRINT SUSER_SNAME()  -- 'TempUser'
    PRINT original_login() -- 'MyDomain\Bob.Smith'

    REVERT;

    /* REVERT did not work */
    print SUSER_SNAME()   -- Still `TempUser'
    print original_login()
END;
GO
gopyfrb3

gopyfrb31#

This is documented here:
REVERT can be specified within a module such as a stored procedure or user-defined function, or as a stand-alone statement. When specified inside a module, REVERT is applicable only to EXECUTE AS statements defined in the module.

REVERT (Transact-SQL)

Even a dynamic SQL nested batch doesn't allow REVERT to change the current identity that the batch was started with, eg

create user alice without login

select user_name()
execute as user='alice'

exec('select user_name();revert;select user_name()')

revert
select user_name()

outputs

-----------
dbo

(1 row affected)

------------
alice

(1 row affected)

------------
alice

(1 row affected)

--------------------------------------------------------------------------------------------------------------------------------
dbo

(1 row affected)

相关问题