SQL Server ->> Revert表达式

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SQL Server ->> Revert表达式相关的知识,希望对你有一定的参考价值。

Revert表达式从SQL Server 2005就有。它的作用是用于切换当前过程的执行上下文返回上一个EXECUTE AS 语句发生之前的安全上下文。Revert可以在存储过程、ad-hoc环境下、用户定义函数中使用。Revert是需要和EXECUTE AS配合使用。

 

这里引用一个MSDN的例子

-- Create two temporary principals.
CREATE LOGIN login1 WITH PASSWORD = J345#$)thb;
CREATE LOGIN login2 WITH PASSWORD = Uor80$23b;
GO
CREATE USER user1 FOR LOGIN login1;
CREATE USER user2 FOR LOGIN login2;
GO
-- Give IMPERSONATE permissions on user2 to user1
-- so that user1 can successfully set the execution context to user2.
GRANT IMPERSONATE ON USER:: user2 TO user1;
GO


-- Display current execution context.
SELECT SUSER_NAME(), USER_NAME();
-- Set the execution context to login1. 
EXECUTE AS LOGIN = login1;
-- Verify that the execution context is now login1.
SELECT SUSER_NAME(), USER_NAME();
-- Login1 sets the execution context to login2.
EXECUTE AS USER = user2;
-- Display current execution context.
SELECT SUSER_NAME(), USER_NAME();
-- The execution context stack now has three principals: the originating caller, login1, and login2.
-- The following REVERT statements will reset the execution context to the previous context.
REVERT;
-- Display the current execution context.
SELECT SUSER_NAME(), USER_NAME();
REVERT;
-- Display the current execution context.
SELECT SUSER_NAME(), USER_NAME();

-- Remove the temporary principals.
DROP LOGIN login1;
DROP LOGIN login2;
DROP USER user1;
DROP USER user2;
GO    

 

REVERT还支持一个WITH COOKIE = @varbinary_variable选项。这个东西的作用主要是为了保证在启动连接池(connection pool)的情况下,当前会话的上下文不被下一个重用会话的人切换。这个东西就像一个密码一样的东西,你保存了密码,就只有你自己知道密码,才能去解码。

 

--Create temporary principal 
CREATE LOGIN login1 WITH PASSWORD = [email protected]$$w0rdO1; 
GO 
CREATE USER user1 FOR LOGIN login1; 
GO

DECLARE @cookie varbinary(100); --variable to store the cookie 
--switch execution context, generate cookie and assign it to variable 
EXECUTE AS USER = user1 WITH COOKIE INTO @cookie;

select @cookie

select CURRENT_USER

EXECUTE AS USER = user2;

-- Use the cookie in the REVERT statement. 
SELECT CURRENT_USER AS UserName;  

DECLARE @cookie varbinary(100); 
-- Set the cookie value to the one from the SELECT @cookie statement. 
SET @cookie = 0x21873959E804DD435976EA5D25B7352431A98B4F144C76F6B1502C5AA3C20F30105842EEA9C361B3DA03B2DBD36E0E070100;
REVERT WITH COOKIE = @cookie; 
-- Verify the context switch reverted. 
SELECT CURRENT_USER AS UserName;  
GO

 

 

 

 

参考:

REVERT (Transact-SQL)

Switching Stored Procedure Execution Context in SQL Server using the REVERT clause

 

以上是关于SQL Server ->> Revert表达式的主要内容,如果未能解决你的问题,请参考以下文章

如何在 SQL 中使用联合创建分类变量?

centos6.9下设置nginx服务开机自动启动

安装SQL SERVER 2008,出现“查找sql server 2008安装媒体”的问题

sql server安装遇到的问题

ms sql2012 能否安装在win2008 server

Sql server2008! SQL server服务无法启动,并显示错误17113, 修复Sql server2008失败!