USER (Transact-SQL)
SQL Server 2005
當未指定預設值時,允許將目前使用者之資料庫使用者名稱的系統提供值插入資料表。
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
社群新增項目
新增
顯示:

