SA0274 : The first statement in the script, must be USE statement
Introduction
Section titled “Introduction”Executing SQL scripts without explicitly specifying the USE statement can result in queries running in the incorrect database context.
Description
Section titled “Description”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:
-- Problematic script without USE statementSELECT * 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 TABLEorALTER 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.
How to fix
Section titled “How to fix”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:
1.Determine the correct target database where the SQL script should execute.
2.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.
3.Review the rest of your script to confirm that all database references and operations align with the designated database context.
For example:
-- Corrected script with USE statementUSE TargetDatabase;SELECT * FROM Users;The rule has a Batch scope and is applied only on the SQL script.
Parameters
Section titled “Parameters”Rule has no parameters.
Remarks
Section titled “Remarks”The rule does not need Analysis Context or SQL Connection.
Effort To Fix
Section titled “Effort To Fix”2 minutes per issue.
Categories
Section titled “Categories”Design Rules
Additional Information
Section titled “Additional Information”There is no additional info for this rule.
Example Test SQL
Section titled “Example Test SQL”SELECT 'Hello, DB1!'
USE DB1
SELECT 'Bye, DB1!'Analysis Results
Section titled “Analysis Results”| Message | Line | Column | |
|---|---|---|---|
| 1 | SA0274 : The first statement in the script, must be USE statement. | 1 | 0 |