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

mtb9vblg  于 2024-01-05  发布在  其他
关注(0)|答案(1)|浏览(114)

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 .

  1. CREATE PROCEDURE Sales.spExec1
  2. AS
  3. BEGIN
  4. PRINT SUSER_SNAME() -- 'MyDomain\Bob.Smith'
  5. PRINT original_login() -- 'MyDomain\Bob.Smith'
  6. EXECUTE AS USER = 'TempUser';
  7. EXEC dbo.spExec2
  8. REVERT;
  9. /* REVERT works in SP where initial EXECUTE AS USER ran */
  10. print SUSER_SNAME() -- 'MyDomain\Bob.Smith'
  11. print original_login() -- 'MyDomain\Bob.Smith'
  12. END;
  13. GO
  14. CREATE PROCEDURE dbo.spExec2
  15. AS
  16. BEGIN
  17. PRINT SUSER_SNAME() -- 'TempUser'
  18. PRINT original_login() -- 'MyDomain\Bob.Smith'
  19. REVERT;
  20. /* REVERT did not work */
  21. print SUSER_SNAME() -- Still `TempUser'
  22. print original_login()
  23. END;
  24. 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

  1. create user alice without login
  2. select user_name()
  3. execute as user='alice'
  4. exec('select user_name();revert;select user_name()')
  5. revert
  6. select user_name()

outputs

  1. -----------
  2. dbo
  3. (1 row affected)
  4. ------------
  5. alice
  6. (1 row affected)
  7. ------------
  8. alice
  9. (1 row affected)
  10. --------------------------------------------------------------------------------------------------------------------------------
  11. dbo
  12. (1 row affected)
展开查看全部

相关问题