USER (Transact-SQL)

當未指定預設值時,允許將目前使用者之資料庫使用者名稱的系統提供值插入資料表。

主題連結圖示Transact-SQL 語法慣例

語法

USER

傳回類型

char

備註

USER 提供與 USER_NAME 系統函數相同的功能。

USER 在 CREATE TABLE 或 ALTER TABLE 陳述式中是搭配 DEFAULT 條件約束使用,或者作為標準函數使用。

USER 一律會傳回目前內容的名稱。在 EXECUTE AS 陳述式之後呼叫 USER 時,USER 會傳回模擬內容的名稱。

如果 Windows 主體利用群組中的成員資格來存取資料庫,則 USER 會傳回 Windows 主體名稱而非群組名稱。

範例

A. 使用 USER 傳回資料庫使用者名稱

下列範例宣告一個變數為 char、將 USER 的目前值指派給這個變數,然後列印這個變數與文字描述。

DECLARE @usr char(30)
SET @usr = user
SELECT 'The current user''s database username is: '+ @usr
GO

以下為結果集:

----------------------------------------------------------------------- 
The current user's database username is: dbo                            

(1 row(s) affected)

B. 搭配 DEFAULT 條件約束來使用 USER

下列範例會使用 USER 作為銷售資料列之銷售員的 DEFAULT 條件約束,來建立資料表。

USE AdventureWorks;
GO
CREATE TABLE inventory22
(
 part_id int IDENTITY(100, 1) NOT NULL,
 description varchar(30) NOT NULL,
 entry_person varchar(30) NOT NULL DEFAULT USER 
)
GO
INSERT inventory22 (description)
VALUES ('Red pencil')
INSERT inventory22 (description)
VALUES ('Blue pencil')
INSERT inventory22 (description)
VALUES ('Green pencil')
INSERT inventory22 (description)
VALUES ('Black pencil')
INSERT inventory22 (description)
VALUES ('Yellow pencil')
GO

下列查詢會選取 inventory22 資料表的所有資訊:

SELECT * FROM inventory22 ORDER BY part_id;
GO

結果集如下 (請注意 entry-person 的值):

part_id     description                    entry_person                   
----------- ------------------------------ -------------------------
100         Red pencil                     dbo                            
101         Blue pencil                    dbo                            
102         Green pencil                   dbo                            
103         Black pencil                   dbo                            
104         Yellow pencil                  dbo                            

(5 row(s) affected)

C. 與 EXECUTE AS 合併使用 USER

下列範例說明在模擬工作階段中進行呼叫時,USER 的行為。

SELECT USER;
GO
EXECUTE AS USER = 'Mario';
GO
SELECT USER;
GO
REVERT;
GO
SELECT USER;
GO

以下為結果集:

DBO
Mario
DBO