How to drop SQL default constraint without knowing its name?
Expanding on Mitch Wheat's code, the following script will generate the command to drop the constraint and dynamically execute it.
declare @schema_name nvarchar(256)
declare @table_name nvarchar(256)
declare @col_name nvarchar(256)
declare @Command nvarchar(1000)
set @schema_name = N'MySchema'
set @table_name = N'Department'
set @col_name = N'ModifiedDate'
select @Command = 'ALTER TABLE ' + @schema_name + '.[' + @table_name + '] DROP CONSTRAINT ' + d.name
from sys.tables t
join sys.default_constraints d on d.parent_object_id = t.object_id
join sys.columns c on c.object_id = t.object_id and c.column_id = d.parent_column_id
where t.name = @table_name
and t.schema_id = schema_id(@schema_name)
and c.name = @col_name
--print @Command
execute (@Command)
Rob Farley's blog post might be of help:
- Two ways to find / drop a default constraint without knowing its name
Something like:
declare @table_name nvarchar(256)
declare @col_name nvarchar(256)
set @table_name = N'Department'
set @col_name = N'ModifiedDate'
select t.name, c.name, d.name, d.definition
from
sys.tables t
join sys.default_constraints d on d.parent_object_id = t.object_id
join sys.columns c on c.object_id = t.object_id
and c.column_id = d.parent_column_id
where
t.name = @table_name
and c.name = @col_name