SA0259 : The created object already exists

Identify and address issues where database objects are unnecessarily re-created in T-SQL scripts.

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:

SQL
1-- Example of problematic declarations
2CREATE TABLE Employees (
3    EmployeeID INT PRIMARY KEY,
4    Name NVARCHAR(100)
5);

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

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:

SQL
 1-- Example of checking existence before creating a table
 2IF NOT EXISTS (SELECT * FROM sys.tables WHERE name = 'Employees')
 3BEGIN
 4    CREATE TABLE Employees (
 5        EmployeeID INT PRIMARY KEY,
 6        Name NVARCHAR(100)
 7    );
 8END
 9
10-- Example using CREATE OR ALTER for a stored procedure
11CREATE OR ALTER PROCEDURE GetEmployeeDetails
12AS
13BEGIN
14    SELECT EmployeeID, Name FROM Employees;
15END

Scope

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

Parameters

Rule has no parameters.

Remarks

The rule requires Analysis Context. If context is missing, the rule will be skipped during analysis.

Effort To Fix
5 minutes per issue.
Categories

Design Rules, Bugs

Additional Information

There is no additional info for this rule.

Example Test SQL
SQL
1CREATE TABLE [Person].[Person]
2(
3        Column1 [int] NOT NULL
4)

Analysis Results
  Message Line Column
1 SA0259 : The created table already exists. 1 22
See Also

Other Resources