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

适用对象:是SQL Server 否Azure SQL 数据库 否Azure Synapse Analytics (SQL DW) 是并行数据仓库 APPLIES TO: yesSQL Server noAzure SQL Database noAzure Synapse Analytics (SQL DW) 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 数据库Azure SQL Database 中,数据库参数只能引用当前数据库。In Azure SQL 数据库Azure 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 数据库,因为即使可以在批处理中使用 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)
主体(数据库引擎) 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)