Transact-SQL 参考

SESSION_USER

是一个 niladic 函数,允许在未指定默认值时将系统为当前会话的用户名提供的值插入到表中。还允许在查询、错误信息等中使用用户名。

语法

SESSION_USER

返回类型

nchar

注释

SESSION_USER 可在 CREATE TABLE 或 ALTER TABLE 语句中与 DEFAULT 约束一起使用,或者用作任何标准函数。

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

下例声明一个 char 类型的变量,并将 SESSION_USER 赋为当前值,然后输出该变量并带有文本描述。

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

下面是结果集:

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

(1 row(s) affected)
B. 将 SESSION_USER 与 DEFAULT 约束一起使用

下例将 SESSION_USER niladic 函数用作 DEFAULT 约束为交货人创建表。

USE pubs
GO
CREATE TABLE deliveries2
(
 order_id int IDENTITY(5000, 1) NOT NULL,
 cust_id  int NOT NULL,
 order_date datetime NOT NULL DEFAULT GETDATE(),
 delivery_date datetime NOT NULL DEFAULT DATEADD(dd, 10, GETDATE()),
 delivery_person char(30) NOT NULL DEFAULT SESSION_USER
)
GO
INSERT deliveries2 (cust_id)
VALUES (7510)
INSERT deliveries2 (cust_id)
VALUES (7231)
INSERT deliveries2 (cust_id)
VALUES (7028)
INSERT deliveries2 (cust_id)
VALUES (7392)
INSERT deliveries2 (cust_id)
VALUES (7452)
GO

以下查询选择 deliveries2 表中的全部信息。

SELECT order_id AS 'Ord#', cust_id AS 'Cust#', order_date, 
   delivery_date, delivery_person AS 'Delivery'
FROM deliveries2
ORDER BY order_id
GO

下面是结果集:

Ord#  Cust#  order_date          delivery_date        Delivery     
----  ------ ------------------  -------------------- ----------------
5000  7510   Mar 4 1998 10:21AM  Mar 14 1998 10:21AM  dbo                            
5001  7231   Mar 4 1998 10:21AM  Mar 14 1998 10:21AM  dbo                            
5002  7028   Mar 4 1998 10:21AM  Mar 14 1998 10:21AM  dbo                            
5003  7392   Mar 4 1998 10:21AM  Mar 14 1998 10:21AM  dbo                            
5004  7452   Mar 4 1998 10:21AM  Mar 14 1998 10:21AM  dbo                            

(5 row(s) affected)

请参见

ALTER TABLE

CREATE TABLE

CURRENT_TIMESTAMP

CURRENT_USER

SYSTEM_USER

系统函数

USER

USER_NAME