In SQL Server 2005 up, you can remove both a constraint and a column in a single expression.
Syntax
ALTER TABLE [ database_name . [ schema_name ] . | schema_name . ] table_name DROP { [ CONSTRAINT ] constraint_name | COLUMN column } [ ,...n ]
The emphasis is on [, ... n] , indicating several terms.
NB! Since the terms are processed sequentially, if the column to be deleted is part of the constraint to be dropped, then the constraint must be the first member followed by a member of the column.
In your example:
ALTER TABLE [dbo].[Employees] DROP CONSTRAINT [DF_Employees_EmpID], COLUMN [EmpID]
So your code will look like this:
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_Employees_EmpID]') AND type = 'D') BEGIN ALTER TABLE [dbo].[Employees] DROP CONSTRAINT [DF_Employees_EmpID], COLUMN [EmpID] END GO
In SQL Server 2016, they introduced the IF EXISTS clause, which eliminates the need to check for constraints first, for example.
ALTER TABLE [dbo].[Employees] DROP CONSTRAINT IF EXISTS [DF_Employees_EmpID], COLUMN IF EXISTS [EmpID]
source share