ORIGINAL_LOGIN (Transact-SQL)

返回连接到 SQL Server 实例的登录名。您可以在具有众多显式或隐式上下文切换的会话中使用该函数返回原始登录的标识。有关上下文切换的详细信息,请参阅了解上下文切换

主题链接图标Transact-SQL 语法约定

语法

ORIGINAL_LOGIN( )

返回类型

sysname

注释

该函数在审核原始连接上下文的标识时非常有用。但是 SESSION_USERCURRENT_USER 之类的函数返回当前的执行上下文,ORIGINAL_LOGIN 返回该会话中首次连接到 SQL Server 实例的登录的标识。

示例

以下示例将当前会话的执行上下文从语句的调用方切换到 login1。函数 SUSER_SNAME 和 ORIGINAL_LOGIN 用于返回当前会话用户(上下文切换到的用户)和原始登录帐户。

USE AdventureWorks2008R2;
GO
--Create a temporary login and user.
CREATE LOGIN login1 WITH PASSWORD = 'J345#$)thb';
CREATE USER user1 FOR LOGIN login1;
GO
--Execute a context switch to the temporary login account.
DECLARE @original_login sysname;
DECLARE @current_context sysname;
EXECUTE AS LOGIN = 'login1';
SET @original_login = ORIGINAL_LOGIN();
SET @current_context = SUSER_SNAME();
SELECT 'The current executing context is: '+ @current_context;
SELECT 'The original login in this session was: '+ @original_login
GO
-- Return to the original execution context
-- and remove the temporary principal.
REVERT;
GO
DROP LOGIN login1;
DROP USER user1;
GO