当未指定默认值时,允许将系统为当前系统用户名提供的值插入表中。
SYSTEM_USER
在 CREATE TABLE 或 ALTER TABLE 语句中将 SYSTEM_USER niladic 函数用在 DEFAULT 约束中,或作为任何标准函数使用。
如果当前用户使用 Windows 身份验证登录到 Microsoft® SQL Server™,SYSTEM_USER 将返回 Windows 2000 或 Windows NT 4.0 登录标识名称,例如"DOMAIN\user_login_name"。然而,如果当前用户使用 SQL Server 身份验证登录到 SQL Server,SYSTEM_USER 将返回 SQL Server 登录标识名称,例如,当用户以 sa 登录时将返回 sa。
本示例声明一个 char 变量,将 SYSTEM_USER 的当前值置于该变量中,然后打印该变量。
DECLARE @sys_usr char(30)
SET @sys_usr = SYSTEM_USER
SELECT 'The current system user is: '+ @sys_usr
GO
下面是结果集:
----------------------------------------------------------
The current system user is: sa
(1 row(s) affected)
本示例创建一个表,将 SYSTEM_USER 用作病人数据行中 receptionist 列的 DEFAULT 约束。
USE pubs
GO
CREATE TABLE appointments2
(
patient_id int IDENTITY(2000, 1) NOT NULL,
doctor_id int NOT NULL,
appt_date datetime NOT NULL DEFAULT GETDATE(),
receptionist varchar(30) NOT NULL DEFAULT SYSTEM_USER
)
GO
INSERT appointments2 (doctor_id)
VALUES (151)
INSERT appointments2 (doctor_id, appt_date)
VALUES (293, '5/15/98')
INSERT appointments2 (doctor_id, appt_date)
VALUES (27882, '6/20/98')
INSERT appointments2 (doctor_id)
VALUES (21392)
INSERT appointments2 (doctor_id, appt_date)
VALUES (24283, '11/03/98')
GO
下面是选择 appointments2 表中所有信息的查询:
SELECT *
FROM appointments2
ORDER BY doctor_id
GO
下面是结果集:
patient_id doctor_id appt_date receptionist
----------- ----------- ------------------------ ---------------
2000 151 Mar 4 1998 10:36AM sa
2001 293 May 15 1998 12:00AM sa
2003 21392 Mar 4 1998 10:36AM sa
2004 24283 Nov 3 1998 12:00AM sa
2002 27882 Jun 20 1998 12:00AM sa
(5 row(s) affected)