SESSION_USER (Transact-SQL)

适用于:SQL ServerAzure SQL 数据库Azure SQL 托管实例Azure Synapse AnalyticsAnalytics Platform System (PDW)

SESSION_USER 返回当前数据库中当前上下文的用户名。

Transact-SQL 语法约定

语法

SESSION_USER  

注意

若要查看 SQL Server 2014 (12.x) 及更早版本的 Transact-SQL 语法,请参阅早期版本文档

返回类型

nvarchar(128)

注解

SESSION_USER 可在 CREATE TABLE 或 ALTER TABLE 语句中与 DEFAULT 约束一起使用,或者将它用作任何标准函数。 如果没有指定默认值,可以将 SESSION_USER 插入表中。 此函数没有参数。 SESSION_USER 可以在查询中使用。

如果在切换上下文之后调用 SESSION_USER,SESSION_USER 将返回模拟上下文的用户名。

示例

A. 使用 SESSION_USER 返回当前会话的用户名

以下示例将变量声明为 nchar,然后将当前值 SESSION_USER 分配给该变量,再与文本说明一起打印此变量。

DECLARE @session_usr NCHAR(30);  
SET @session_usr = SESSION_USER;  
SELECT 'This session''s current user is: '+ @session_usr;  
GO  

这是会话用户为 Surya 时的结果集:

--------------------------------------------------------------
This session's current user is: Surya

(1 row(s) affected)

B. 与 DEFAULT 约束一起使用 SESSION_USER

以下示例创建一个表,该表使用 SESSION_USER 作为记录发货回执者的名字的 DEFAULT 约束。

USE AdventureWorks2022;  
GO  
CREATE TABLE deliveries3  
(  
 order_id INT IDENTITY(5000, 1) NOT NULL,  
 cust_id  INT NOT NULL,  
 order_date SMALLDATETIME NOT NULL DEFAULT GETDATE(),  
 delivery_date SMALLDATETIME NOT NULL DEFAULT   
    DATEADD(dd, 10, GETDATE()),  
 received_shipment NCHAR(30) NOT NULL DEFAULT SESSION_USER  
);  
GO  

添加到表中的记录将以当前用户的用户名为戳记。 在此示例中,WanidaSylvesterAlejandro 将验证发货的回执。 这可以通过使用 EXECUTE AS 来切换用户上下文进行模拟。

EXECUTE AS USER = 'Wanida'  
INSERT deliveries3 (cust_id)  
VALUES (7510);  
INSERT deliveries3 (cust_id)  
VALUES (7231);  
REVERT;  
EXECUTE AS USER = 'Sylvester'  
INSERT deliveries3 (cust_id)  
VALUES (7028);  
REVERT;  
EXECUTE AS USER = 'Alejandro'  
INSERT deliveries3 (cust_id)  
VALUES (7392);  
INSERT deliveries3 (cust_id)  
VALUES (7452);  
REVERT;  
GO  

下面的查询从 deliveries3 表中选择所有信息。

SELECT order_id AS 'Order #', cust_id AS 'Customer #',   
   delivery_date AS 'When Delivered', received_shipment   
   AS 'Received By'  
FROM deliveries3  
ORDER BY order_id;  
GO  

下面是结果集。

Order #   Customer #  When Delivered       Received By
--------  ----------  -------------------  -----------
5000      7510        2005-03-16 12:02:14  Wanida
5001      7231        2005-03-16 12:02:14  Wanida
5002      7028        2005-03-16 12:02:14  Sylvester
5003      7392        2005-03-16 12:02:14  Alejandro
5004      7452        2005-03-16 12:02:14  Alejandro

(5 row(s) affected)

示例:Azure Synapse Analytics 和 Analytics Platform System (PDW)

C:使用 SESSION_USER 返回当前会话的用户名

以下示例返回当前会话的会话用户。

SELECT SESSION_USER;  

另请参阅

ALTER TABLE (Transact-SQL)
CREATE TABLE (Transact-SQL)
CURRENT_TIMESTAMP (Transact-SQL)
CURRENT_USER (Transact-SQL)
SYSTEM_USER (Transact-SQL)
系统函数 (Transact-SQL)
USER (Transact-SQL)
USER_NAME (Transact-SQL)