SQL Server error 915 occurs when trying to execute a script that targets a specific database level, but SQL Server cannot determine the current script level—often due to missing or incorrect context, especially in multi-database or cross-database scripts. This typically happens when using USE [database] before a script that includes schema-level operations (like CREATE TABLE or ALTER SCHEMA) within certain tools (SSMS, Azure Data Studio, or CLI tools) and the script level isn’t explicitly set or is ambiguous. The fix involves ensuring the correct database context is established and using proper batch separators or explicit schema declarations. No external tools are required—just SSMS or equivalent, and appropriate permissions.
What You'll Need
- SQL Server Management Studio (SSMS) version 18.0 or later (or Azure Data Studio)
- Valid login with
CREATE TABLE,ALTER SCHEMA, orALTER ANY SCHEMApermissions in the target database - A working knowledge of T-SQL batch syntax and the
USEstatement - The target database must exist and be online (not in
OFFLINE,RESTORING, orRECOVERINGstate)
Step-by-Step
- Verify the database exists and is accessible
RunSELECT name, state_desc FROM sys.databases WHERE name = 'YourDatabaseName'in the context ofmaster. If the database is missing, offline, or in an error state (e.g.,SUSPECT), resolve that first—restore from backup or bring it online usingALTER DATABASE [YourDatabaseName] SET ONLINE(only if safe to do so). - Ensure correct batch separation using
GO
In SSMS or Azure Data Studio, T-SQL scripts are executed in batches separated by theGOcommand. If you useUSE [Database]followed immediately by schema-modifying statements withoutGO, SQL Server may treat them as a single batch and lose context. PlaceGOon its own line *after* theUSEstatement and *before* any schema operations. For example:USE [AdventureWorks2019]; GO CREATE TABLE dbo.TestTable (ID INT); GO
Do not placeGObetweenUSEand the next statement—put it *after*USEto finalize the context switch. - Avoid inline
USEwithin multi-line scripts
If your script includes conditional logic (e.g.,IF EXISTS) or variables declared before theUSEstatement, SQL Server may evaluate the entire block as one scope, preventingUSEfrom taking effect for later statements. MoveUSEto the very top of a new script window, execute it alone withGO, then write and run subsequent commands in separate batches. - Set the database context explicitly in the Object Explorer
In SSMS, right-click your database under "Databases" in Object Explorer and select "New Query". This opens a new query window already scoped to that database, eliminating reliance onUSE. Now run your schema-modifying script directly withoutUSE—this is the most reliable way to avoid error 915. - Check for nested contexts in stored procedures or functions
Never useUSEinside a stored procedure, function, or trigger—SQL Server ignoresUSEin these contexts and will throw error 915 when referencing schema objects. Instead, use fully qualified names (e.g.,AdventureWorks2019.dbo.TableName) or restructure the logic to run outside the procedure. - Confirm the current database with
DB_NAME()
Before executing critical scripts, runSELECT DB_NAME() AS CurrentDatabaseto verify your context. If it returnsmasteror an unexpected database, re-runUSE [CorrectDB]; GOand confirm withDB_NAME()again.
Common Mistakes
- Forgetting
GOafterUSE, causing subsequent statements to run in the wrong database - Running
USEinside a transaction or dynamic SQL block—this does not persist context - Assuming
USEcarries over between query windows—each window starts fresh inmasterunless explicitly changed - Using
EXEC('USE [DB]; ...')and expecting the innerUSEto affect the outer session - Running scripts from command-line tools (like
sqlcmd) without the-dparameter to set the database, then relying onUSEin the script file
Tips
- Always prefix objects with schema names (e.g.,
dbo.TableName) to avoid ambiguity—even withoutUSE, this prevents context issues - Use SSMS’s "Query > Query Options > Execution > Connection" to set a default database for new queries, reducing reliance on
USE - When scripting from Object Explorer, right-click a table or schema object and choose "Script Table as > CREATE To > New Query Editor Window"—this auto-uses the correct database context
- Azure SQL Database users: avoid
USEentirely, as cross-database queries are limited; use linked servers or external tables instead - Test scripts in a non-production database first to isolate context-related issues
- Enable "SQLCMD mode" in SSMS (Query > SQLCMD Mode) only if you intend to use
:setvarand:connectcommands—but note this changes batch behavior and may require rewrites
Troubleshooting
If error 915 persists after following the steps above, proceed systematically:
- Restart SSMS
Closing and reopening SSMS clears any cached session state that might interfere with context switching. Reconnect and re-run the script in a new window. - Check for blocked processes
RunSELECT * FROM sys.dm_exec_requests WHERE blocking_session_id <> 0inmaster. A blocking session onsys.databasesor metadata views can delay context resolution—kill the blocker if safe (e.g.,KILL <session_id>). - Verify permissions explicitly
Even if logged in assysadmin, some tools (like Azure Data Studio with Azure AD) may not immediately elevate context. Confirm your login hasdb_owneror equivalent in the target database withSELECT IS_MEMBER('db_owner') AS IsDbOwnerafter switching databases. - Test with minimal script
Create a new query window and run only:USE [YourDatabase]; GO SELECT 1;
If this succeeds, gradually add complexity (e.g.,CREATE TABLE) until the error reappears—this isolates the problematic statement. - Check for database mirroring or availability groups
If the database is part of an Always On availability group, ensure you are connecting to the primary replica. Secondary replicas are read-only and may fail context-sensitive operations. RunSELECT ars.role_desc FROM sys.dm_hadr_availability_replica_states ars JOIN sys.databases db ON ars.group_id = db.group_id WHERE db.name = 'YourDatabase'to confirm role. - Update SSMS
Older versions of SSMS (pre-18.0) have known bugs with script-level resolution. Download the latest from the official Microsoft site and reinstall—this fixes edge-case parsing issues in the query engine.
Frequently Asked Questions
Can I use USE in a stored procedure to change databases?
No—SQL Server ignores USE inside stored procedures, functions, or triggers. Use fully qualified names (e.g., Server.Database.Schema.Table) or execute dynamic SQL with EXEC('SELECT ...') AT LinkedServer for cross-server queries.
Why does USE work in one query window but not another?
Each query window maintains its own session context. Changing the database in one window does not affect others. You must set the context individually in each window or use the "New Query" shortcut from Object Explorer to pre-select the database.
Does error 915 occur in Azure SQL Database?
Yes—but less commonly. Azure SQL Database restricts cross-database queries, soUSE may not persist as expected. Always connect directly to the target database using the connection string’s Initial Catalog parameter instead of relying on USE.
Can a missing GO cause other errors besides 915?
Absolutely. Without GO, variables declared before a USE statement remain in scope but refer to the wrong database, causing "invalid object name" errors or unexpected data modifications. GO is essential for separating batches where context or scope changes.
Is there a server setting to disable USE entirely?
No—USE is a core T-SQL command and cannot be disabled at the server level. However, Azure SQL Database restricts cross-database access by default, and some managed services (like Azure Synapse) limit its use in specific contexts.
Does this error affect backup or restore operations?
No—backup and restore commands (e.g.,BACKUP DATABASE) operate in the context of master and do not require or support USE. Error 915 is specific to schema-modifying or data-definition language (DDL) scripts that rely on current database context.