I’m a T-SQl and database newbie, and a little confused.
In the T-SQL book I’m reading it says that a USE statement is written to set the database context of the session. Does that mean that there can be more than one database in an instance of SQL-server and the USE statement tells SQL server which database the query will be on?
I’m a T-SQl and database newbie, and a little confused. In the T-SQL book
Share
It’s not quite as simple as that. Yes, a server can have multiple databases, but I would caution against using a
USEstatement unless all of your queries are that way.Every connection to SQL server has a “current database”. That means that any query run over that connection will use that database (though it’s possible to access information from other databases by explicitly indicating this with dot notation). The
USEstatement changes the current database for the connection, so if one statement expects to run in theMyDatabasedatabase (but doesn’t specify it with aUSE MyDatabasestatement) and another query executesUse OtherDatabase, then the first query will fail when run.For instance:
MyDatabasedatabaseselect * from sometableExecute the next query:
use OtherDatabaseselect * from othertableIf we try to execute the first query again it will fail (assuming that
sometabledoesn’t also exist inOtherDatabase) because we’ve changed the context of the connection with theUSEstatement. The upshot here is that theUSEstatement is connection-wide, not specific to an individual query.In software development, the more common approach is to maintain a connection to the server for each database you plan to query against. That means that the query against
MyDatabasewill use a different connection than the one used by the query forOtherDatabase. This helps mitigate the possibility of a change in query context causing queries to fail.