USE (TSQL Statement)

Changes the current database.

Syntax

USE database

Arguments

database
is the name of the database which will become the current database name. It is an identifier.

Remarks

The current database name is used when the batch is compiled, to complete object names if the database part of the qualified name is missing.

When a script file contains many batches, the current database value at the end of each batch is passed to the next batch.

If database is not found, an error is raised and the whole session aborts.

Examples

USE mydb;
PRINT 'Current database is ' + DB_NAME();

-- same as CREATE TABLE mydb.dbo.clients
CREATE TABLE clients (id INT NOT NULL IDENTITY PRIMARY KEY, name VARCHAR(30) NOT NULL);
GO

PRINT 'Current database is ' + DB_NAME(); <--- the current database is inherited from the previous batch

-- same as INSERT INTO mydb.dbo.clients
INSERT INTO clients VALUES ('John'), ('Maria'), ('Hayley');

-- same as SELECT * FROM mydb.dbo.clients
SELECT * FROM clients;

The result is:

2016/03/30 20:08:33 --- executing batch example.sql:19 ---
Current database is mydb
2016/03/30 20:08:33 return code: 0

2016/03/30 20:08:33 --- executing batch example.sql:24 ---
Current database is mydb
(3 row(s) affected)

id         |name           |
-----------+---------------+
          1|John           |
          2|Maria          |
          3|Hayley         |

(3 row(s) affected)

2016/03/30 20:08:33 return code: 0