SQL Server Management Studio – SQL Script Scope for Active or All Databases

functionsscriptingsql-server-2008stored-procedures

I'm not very familiar with SQL Server, more familiar with MySQL.

I'm used to seeing everything in code, whereas SQL Server, some things are done with buttons. In MySQL, I'd execute USE testing_database and then I'd know my subsequent queries would execute against that database.

In SQL Server Management Studio, I see that my "Testing Database" is selected in the dropdown select. Does that mean that the queries in the script will execute ONLY against that database?

The script does not include any references to database names. It uses sp_msdependencies to populate a list of Views and then acts on that list. Will sp_msdependencies execute only against the current database?

There are several other databases besides the testing database that I do not want to touch with this test.

Best Answer

If you execute a use database statement, subsequent queries will only execute against that db. However: this is only for the current tab.

In SSMS to see the connection context look in the bottom right corner of the current tab. You should see the current database name there.

Or you could query the current db with:

SELECT DB_NAME() AS [Current Database];

Note: it is possible to have multiple tabs open which can be connected to different databases or servers. If you have multiple tabs open and tiled it can get a bit confusing.

As an added precaution you could disconnect and close other tabs to prevent any accidents.

It is possible that a sql script can contain many sql statements, and could include another use database command which could change the connection part way through the script. You should read the script or search for this before executing scripts supplied by other people.

One last warning: it is also possible to connect to multiple database servers simultaneously using registered servers. However unless you deliberately chose to do this its extremely unlikely you would ever encounter this even accidentally.