Use Server name with database

Mike 341 Reputation points
2020-12-01T14:03:59.027+00:00

Hi, How I can USE command with Server name and with database?

Use <Servername>.<DataBase>

Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,552 questions
0 comments No comments
{count} votes

Accepted answer
  1. Dan Guzman 9,206 Reputation points
    2020-12-01T15:59:02.997+00:00

    The T-SQL USE statement only allows a database name specification. It is up to the client application or tool to connect to the desired server before executing USE.

    SSMS (in SQLCMD mode) and the SQLCMD utility provide a CONNECT command to dynamically change the database connection. You can include a CONNECT command in scripts executed with these tools. The server and database context reverts back to the initial server and database after script execution For example:

    :CONNECT .
    USE master;
    SELECT @@SERVERNAME AS CurrentServer, DB_NAME() AS CurrentDatabase;
    GO
    
    1 person found this answer helpful.
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Yitzhak Khabinsky 24,946 Reputation points
    2020-12-01T14:18:51.357+00:00

    You can't.

    <servername> is a property of a connection to a MS SQL Server instance.
    Just after you already connected to an instance, you can use T-SQL:
    USE <database>;

    Official documentation: use-transact-sql

    2 people found this answer helpful.
    0 comments No comments