Total PageViews

Friday, January 15, 2021

How to find and dynamically delete the default constraint in MS SQL Server

 When we have a condition to delete the constraint where the name of constraint is generated by the database as default then

declare @schema_name Varchar(100)

declare @table_name Varchar(100)

declare @col_name Varchar(100)

declare @Command  varchar(500)

set @schema_name = 'Scott'

set @table_name = 'Employee'

set @col_name = 'IsAdmin'

 

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)


When we execute this block it will find the constraint details of that column and drop the default constraint.


What other ideas can you add to this post that I may have not mentioned?


No comments:

Post a Comment