Prior to SQL Server 2016, when we need to drop a SQL Object, it's the best practice to check whether the respective object exists or not. Otherwise, the operation will return in an error.
DROP TABLE [SomeTable]
If the object is not found, it will return the following error:
Msg 3701, Level 11, State 5, Line 11
Cannot drop the table 'SomeTable', because it does not exist or you do not have permission.
Hence, we need to change the syntax as:
IF EXISTS(SELECT 'x' FROM sys.objects AS O WHERE O.name = 'SomeTable' AND O.[type] = 'U')
DROP TABLE [SomeTable]
IF OBJECT_ID('dbo.SomeTable','U') IS NOT NULL
DROP TABLE [SomeTable]
In SQL Server 2016, there is an easier way to do this using comparatively less amount for coding.
DROP TABLE IF EXISTS [SomeTable];
DROP PROCEDURE IF EXISTS [SomeProcedure];
Even this can be used when dropping columns and constraints from a table.
ALTER TABLE [TableName] DROP CONSTRAINT IF EXISTS [ConstraintName]
ALTER TABLE [TableName] DROP COLUMN IF EXISTS [TableName]
Example:
CREATE TABLE SomeTable(
Id INT
,Name VARCHAR(10) NOT NULL CONSTRAINT [DF_SomeTable_Name] DEFAULT ('')
)
ALTER TABLE dbo.SomeTable
DROP CONSTRAINT IF EXISTS [DF_SomeTable_Name]
ALTER TABLE dbo.SomeTable
DROP COLUMN IF EXISTS [Name]
The beauty of this functionality is that even the object does not exist, it will not fail and execution will continue.
Currently, the following objects can be dropped with the DIE functionality:
ASSEMBLY
VIEW
DATABASE
DEFAULT
FUNCTION
PROCEDURE
INDEX
AGGREGATE
ROLE
RULE
SCHEMA
SECURITY POLICY
SEQUENCE
SYNONYM
TABLE
TRIGGER
TYPE
USER
VIEW
Hope this will be useful to you.
My passion lies in building business intelligence and data-based solutions, writing about things I work with and talking about it. New technologies relevant to my line of work interest me and I am often seen playing with early releases of such technologies.
My current role involves architecting and building a variety of data solutions, providing database maintenance and administration support, building the organization’s data practice, and training and mentoring peers.
My aspiration over the next several years is to achieve higher competency and recognition in the field of Data Analytics and move into a career of data science.
Specialities: SQL Server, T-SQL Development, SQL Server Administration, SSRS, SSIS, C#, ASP.Net, Crystal Reports