SA0274 : The first statement in the script, must be USE statement |
![]() |
Executing SQL scripts without explicitly specifying the USE statement can result in queries running in the incorrect database context.

In SQL Server, omitting the USE statement at the beginning of a script might cause it to execute within an unintended database. This is particularly problematic in environments with multiple databases, as it can lead to unexpected data modifications and operational issues.
For example:
1-- Problematic script without USE statement 2SELECT * FROM Users;
This example assumes execution in a specific database. If run against the wrong one, it risks data views or modifications not aligned with the intended operation, leading to various issues:
-
Data Integrity Risks: Unintended modifications or deletions in a wrong database, impacting data integrity.
-
Schema Mismatches: Executing DDL commands, such as CREATE TABLE or ALTER PROCEDURE, in the wrong context may lead to incorrect schema deployments.
-
Operational Failures: Scripts might fail due to missing required objects in the current database context.

Ensure the correct database context by explicitly specifying the target database at the beginning of your SQL script using the USE statement to prevent operational errors and unintended data modifications.
Follow these steps to address the issue:
-
Determine the correct target database where the SQL script should execute.
-
Add a USE statement at the start of your SQL script, specifying the intended database name. This ensures that all subsequent commands execute within this database context.
-
Review the rest of your script to confirm that all database references and operations align with the designated database context.
For example:
1-- Corrected script with USE statement 2USE TargetDatabase; 3SELECT * FROM Users;

The rule has a Batch scope and is applied only on the SQL script.

Rule has no parameters.

The rule does not need Analysis Context or SQL Connection.


Design Rules, New Rules

There is no additional info for this rule.

SQL
1SELECT 'Hello, DB1!' 2 3 4USE DB1 5 6 7SELECT 'Bye, DB1!' |

Message | Line | Column | |
---|---|---|---|
1 | SA0274 : The first statement in the script, must be USE statement. | 1 | 0 |
