sqlsql-serverdatabasevisual-studiodatabase-server

Use a specific database and table in MSSQL (Visual Studio)


I am working in Visual Studio and using the SQL manager built into the studio. Now I am connecting to several databases and I would very much like to be able to save and open my SQL queries and still have them access the correct database and table.

So:

Database servers:
db.company.com
    databasenumber1
    databasenumber2
    databasenumber3
db2.company.com
    databasenumber1
    databasenumber2
    databasenumber3
db3.company.com
    databasenumber1
    databasenumber2
    databasenumber3

Now I wish to write an sql query that does something simple, lets say:

select * from users where userid = '12';

However I want to select this from database server db2 and from database databasenumber3.

How do I write that in a use statement? Or is there something other than "use"??


Solution

  • Working among several databases in once script file requires USE followed by GO statement.

    USE db1;
    GO
    
    SQL statements ...
    ...
    
    
    USE db2;
    GO
    
    SQL statements ...
    ...
    

    Another option is to use server.dbname.tablename format but that strictly requires that all of your databases are hosted on same server.

    SELECT * FROM server.db1.table1  
    SELECT * FROM server.db2.table2
    ...