Skip to content

SA0259 : The created object already exists

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

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 declarations
CREATE 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.

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 table
IF 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 procedure
CREATE OR ALTER PROCEDURE GetEmployeeDetails
AS
BEGIN
SELECT EmployeeID, Name FROM Employees;
END

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

Rule has no parameters.

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

5 minutes per issue.

Design Rules, Bugs

There is no additional info for this rule.

CREATE TABLE [Person].[Person]
(
Column1 [int] NOT NULL
)
  Message Line Column
1 SA0259 : The created table already exists. 1 22

Analysis Rules