When to start a T-SQL query using USE?

I am new to T-SQl and the database and a bit confused. The T-SQL book I am reading says that the USE statement is used to set the database context for writing. Does this mean that there can be several databases in the instance of the SQL server, and the USE statement tells the SQL server in which database the query will be indicated?

+3
source share
7 answers

It's not so easy. Yes, a server can have several databases, but I would caution against using the instructions USEif all your queries are not like that.

SQL- " ". , , , ( , ). USE , , MyDatabase ( USE MyDatabase), Use OtherDatabase, .

:

  • SQL Server MyDatabase
  • :

select * from sometable

  • :

    Use OtherDatabase

    select * from othertable

, (, sometable OtherDatabase), USE. , USE , .

, . , MyDatabase , , OtherDatabase. , .

+5

, SQL Server .

+3

, SQL Server . .

Management Studio USE .

+2

, . DB .

"USE", , . ( ), , .

database.schema.sqlobject (sqlobject - , , SP ..)

:

SELECT * FROM myDbOfBirds.dbo.MigratoryTable

USE myDbOfBirds
GO
SELECT * 
-- note how we don't explicity qualify MigratoryTable table (can but do not have to)
-- but that we do so for the Country table  (have to)
FROM MigratoryTable  MT
JOIN MyOtherDB.dbo.Country C ON C.CountryCode = MT.CountryCode
WHERE MigrationMonth = 11

, , , USE - , , . , USE , ( )

+2

( ); USE, .

+1

"use", . , tho.

sql- , . , .

SQL Server 32 767.

+1

, SQL Server . USE SQL Server .

The USE statement is often used to prevent "accidental" query execution in the wrong database. For example, before running a script that creates or deletes tables, you can add the USE statement at the top to reduce the risk of accidentally running the script in the main database.

However, in most scenarios, the USE operator is not required because the connection string used to connect to the server will also contain the database.

+1
source

Source: https://habr.com/ru/post/1727245/


All Articles