SA0259 : The created object already exists
Introduction
Section titled “Introduction”Identify and address issues where database objects are unnecessarily re-created in T-SQL scripts.
Description
Section titled “Description”When creating databases, schemas, procedures, views, functions, triggers, tables, or indexes in SQL Server, it can be problematic to use plain CREATE statements if the objects already exist. This can lead to errors or unintended overwrites that disrupt database functionality.
For example:
-- Example of problematic declarationsCREATE TABLE Employees ( EmployeeID INT PRIMARY KEY, Name NVARCHAR(100));If the Employees table already exists, this statement will fail and could cause issues during deployment or script execution. It is essential to check for the existence of the object before creating it or use conditional statements to manage such scenarios effectively.
-
Deployment scripts may fail due to existing objects, leading to manual intervention or errors.
-
Potential for data loss or corruption if objects are inadvertently overwritten.
-
Increased maintenance overhead to ensure objects are managed without conflicts.
How to fix
Section titled “How to fix”This section outlines the steps to prevent unnecessary re-creation of SQL objects by checking for existence or using conditional creation techniques.
Follow these steps to address the issue:
1.Check if the object already exists before creating it by using the IF NOT EXISTS construct.
2.For stored procedures, functions, triggers, and views, use the CREATE OR ALTER statement to ensure the object is either created or modified if it already exists.
3.For tables and other objects that cannot be altered, use the IF NOT EXISTS pattern to avoid errors during creation.
For example:
-- Example of checking existence before creating a tableIF NOT EXISTS (SELECT * FROM sys.tables WHERE name = 'Employees')BEGIN CREATE TABLE Employees ( EmployeeID INT PRIMARY KEY, Name NVARCHAR(100) );END
-- Example using CREATE OR ALTER for a stored procedureCREATE OR ALTER PROCEDURE GetEmployeeDetailsASBEGIN SELECT EmployeeID, Name FROM Employees;ENDThe 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 requires Analysis Context. If context is missing, the rule will be skipped during analysis.
Effort To Fix
Section titled “Effort To Fix”5 minutes per issue.
Categories
Section titled “Categories”Design Rules, Bugs
Additional Information
Section titled “Additional Information”There is no additional info for this rule.
Example Test SQL
Section titled “Example Test SQL”CREATE TABLE [Person].[Person]( Column1 [int] NOT NULL)Analysis Results
Section titled “Analysis Results”| Message | Line | Column | |
|---|---|---|---|
| 1 | SA0259 : The created table already exists. | 1 | 22 |