USE (Transact-SQL)USE (Transact-SQL)

適用於: 是SQL Server 否Azure SQL Database 否Azure SQL 資料倉儲 是平行處理資料倉儲 APPLIES TO: yesSQL Server noAzure SQL Database noAzure SQL Data Warehouse yesParallel Data Warehouse

SQL ServerSQL Server 中將資料庫內容變更為指定的資料庫或資料庫快照集。Changes the database context to the specified database or database snapshot in SQL ServerSQL Server.

主題連結圖示 Transact-SQL 語法慣例Topic link icon Transact-SQL Syntax Conventions

語法Syntax

USE { database_name }   
[;]  

引數Arguments

database_namedatabase_name
這是使用者內容所要切換的資料庫或資料庫快照集的名稱。Is the name of the database or database snapshot to which the user context is switched. 資料庫和資料庫快照集名稱必須符合識別碼的規則。Database and database snapshot names must comply with the rules for identifiers.

Azure SQL DatabaseAzure SQL Database 中,資料庫參數只能參考目前資料庫。In Azure SQL DatabaseAzure SQL Database, the database parameter can only refer to the current database. 如果提供目前資料庫以外的資料庫,則 USE 陳述式不會在資料庫之間切換,並且會傳回錯誤碼 40508。If a database other than the current database is provided, the USE statement does not switch between databases, and error code 40508 is returned. 若要變更資料庫,您必須直接連接到資料庫。To change databases, you must directly connect to the database. USE 陳述式在此頁面頂端標示為不適用於 SQL Database,因為即使您可在批次中加入 USE 陳述式,它也不會執行任何動作。The USE statement is marked as not applicable to SQL Database at the top of this page, because even though you can have the USE statement in a batch, it doesn't do anything.

RemarksRemarks

SQL ServerSQL Server 登入連接到 SQL ServerSQL Server 時,會自動連接到預設的資料庫並取得資料庫使用者的安全性內容。When a SQL ServerSQL Server login connects to SQL ServerSQL Server, the login is automatically connected to its default database and acquires the security context of a database user. 如果尚未針對 SQL ServerSQL Server 登入建立資料庫使用者,登入就會以 guest 的身分連接。If no database user has been created for the SQL ServerSQL Server login, the login connects as guest. 如果資料庫使用者沒有資料庫的 CONNECT 權限,USE 陳述式將會失敗。If the database user does not have CONNECT permission on the database, the USE statement will fail. 如果尚未為登入指派預設的資料庫,則其預設資料庫將會設定為 master。If no default database has been assigned to the login, its default database will be set to master.

USE 執行於編譯和執行階段,且會立即生效。USE is executed at both compile and execution time and takes effect immediately. 因此,會在指定的資料庫中,執行批次中出現在 USE 陳述式之後的陳述式。Therefore, statements that appear in a batch after the USE statement are executed in the specified database.

權限Permissions

需要目標資料庫的 CONNECT 權限。Requires CONNECT permission on the target database.

範例Examples

下列範例會將資料庫內容變更為 AdventureWorks2012 資料庫。The following example changes the database context to the AdventureWorks2012 database.

USE AdventureWorks2012;  
GO  

另請參閱See Also

CREATE LOGIN (Transact-SQL) CREATE LOGIN (Transact-SQL)
CREATE USER (Transact-SQL) CREATE USER (Transact-SQL)
主體 (Database Engine) Principals (Database Engine)
CREATE DATABASE (SQL Server Transact-SQL) CREATE DATABASE (SQL Server Transact-SQL)
DROP DATABASE (Transact-SQL) DROP DATABASE (Transact-SQL)
EXECUTE (Transact-SQL)EXECUTE (Transact-SQL)