SQL Server模擬別的賬戶登入

edwardking888發表於2011-07-15
使用 EXECUTE AS 和 REVERT 切換上下文(適用於SQL SERVER 2005以上版本
USE AdventureWorks2008R2;
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;
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

如果是在SQL SERVER 2000系統下,則可以使用SETUSER命令:

SETUSER 'mary'
GO
GRANT SELECT ON computer_types TO joe
GO
SETUSER

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/8183550/viewspace-702266/,如需轉載,請註明出處,否則將追究法律責任。

相關文章