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, or ALTER ANY SCHEMA permissions in the target database
  • A working knowledge of T-SQL batch syntax and the USE statement
  • The target database must exist and be online (not in OFFLINE, RESTORING, or RECOVERING state)

Step-by-Step

  1. Verify the database exists and is accessible
    Run SELECT name, state_desc FROM sys.databases WHERE name = 'YourDatabaseName' in the context of master. If the database is missing, offline, or in an error state (e.g., SUSPECT), resolve that first—restore from backup or bring it online using ALTER DATABASE [YourDatabaseName] SET ONLINE (only if safe to do so).
  2. Ensure correct batch separation using GO
    In SSMS or Azure Data Studio, T-SQL scripts are executed in batches separated by the GO command. If you use USE [Database] followed immediately by schema-modifying statements without GO, SQL Server may treat them as a single batch and lose context. Place GO on its own line *after* the USE statement and *before* any schema operations. For example:
    USE [AdventureWorks2019];
    GO
    CREATE TABLE dbo.TestTable (ID INT);
    GO
    Do not place GO between USE and the next statement—put it *after* USE to finalize the context switch.
  3. Avoid inline USE within multi-line scripts
    If your script includes conditional logic (e.g., IF EXISTS) or variables declared before the USE statement, SQL Server may evaluate the entire block as one scope, preventing USE from taking effect for later statements. Move USE to the very top of a new script window, execute it alone with GO, then write and run subsequent commands in separate batches.
  4. 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 on USE. Now run your schema-modifying script directly without USE—this is the most reliable way to avoid error 915.
  5. Check for nested contexts in stored procedures or functions
    Never use USE inside a stored procedure, function, or trigger—SQL Server ignores USE in 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.
  6. Confirm the current database with DB_NAME()
    Before executing critical scripts, run SELECT DB_NAME() AS CurrentDatabase to verify your context. If it returns master or an unexpected database, re-run USE [CorrectDB]; GO and confirm with DB_NAME() again.

Common Mistakes

  • Forgetting GO after USE, causing subsequent statements to run in the wrong database
  • Running USE inside a transaction or dynamic SQL block—this does not persist context
  • Assuming USE carries over between query windows—each window starts fresh in master unless explicitly changed
  • Using EXEC('USE [DB]; ...') and expecting the inner USE to affect the outer session
  • Running scripts from command-line tools (like sqlcmd) without the -d parameter to set the database, then relying on USE in the script file

Tips

  • Always prefix objects with schema names (e.g., dbo.TableName) to avoid ambiguity—even without USE, 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 USE entirely, 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 :setvar and :connect commands—but note this changes batch behavior and may require rewrites

Troubleshooting

If error 915 persists after following the steps above, proceed systematically:

  1. 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.
  2. Check for blocked processes
    Run SELECT * FROM sys.dm_exec_requests WHERE blocking_session_id <> 0 in master. A blocking session on sys.databases or metadata views can delay context resolution—kill the blocker if safe (e.g., KILL <session_id>).
  3. Verify permissions explicitly
    Even if logged in as sysadmin, some tools (like Azure Data Studio with Azure AD) may not immediately elevate context. Confirm your login has db_owner or equivalent in the target database with SELECT IS_MEMBER('db_owner') AS IsDbOwner after switching databases.
  4. 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.
  5. 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. Run SELECT 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.
  6. 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, so USE 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.