execute as login 切换上下文


作为DBA,可能经常需要帮助Developer排除有关权限的问题。要确认某个账号是不是已经拥有了某权限,DBA并不需要使用该账号的登录名和密码进行验证,只需使用execute as语句,将当前会话的上下文切换到指定的login(登录)或者user(用户),就可以验证该账号是否拥有某权限。

 

execute as user='user_name'

该语句模拟的上下文是当前数据库中的user,模拟范围仅限于当前数据库,任何对该数据库以外的资源的访问尝试都会导致失败,不管该user是否拥有相应权限。

 

execute as login='login_name'

该语句模拟的上下文是一个login,模拟范围处于服务器级别,可以访问当前数据库之外的资源,只要该login拥有相应权限。

select spid,loginame from master..sysprocesses where spid=@@spid

查看当前的登录名和用户名

SELECT SUSER_NAME(), USER_NAME();

 

 


USE AdventureWorksLT2008R2;

GO

--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;

--REVOKE 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 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 current execution context.

SELECT SUSER_NAME(), USER_NAME();

REVERT;

--Display current execution context.

SELECT SUSER_NAME(), USER_NAME();


--Remove temporary principals.

DROP LOGIN login1;

DROP LOGIN login2;

DROP USER user1;

DROP USER user2;

GO

转载于:https://www.cnblogs.com/dotagg/p/6372048.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值