It's one of the common question while deleting column from a table. How we will delete a column having default constraint. If we try to delete a column having Default constraint, then it will raise error.
Looking for Answer, here we go:
Declare two variables as:
DECLARE @ConstraintName NVARCHAR(200), @sql NVARCHAR(MAX)
Now set the value of @ConstraintName as Default constraint name:
SET @ConstraintName = (SELECT NAME AS DEFAULT_CONSTRAINT_NAME
FROM SYS.DEFAULT_CONSTRAINTS
WHERE OBJECT_NAME(PARENT_OBJECT_ID) = '<Table_Name>')
After this create run-time query to delete constraint and set it to @sql:
SET @sql = N'ALTER TABLE <Table_Name> DROP CONSTRAINT ' + @ConstraintName
And with the help of sp_executesql drop the constraint as:
EXEC sp_executesql @sql
And as constraint is deleted so finally delete the column without any error.
ALTER TABLE <Table_Name> DROP COLUMN <Column_Name>
Here is complete script for copy paste champs..;)
DECLARE @ConstraintName NVARCHAR(200), @sql
NVARCHAR(MAX)
SET @ConstraintName = (SELECT NAME AS DEFAULT_CONSTRAINT_NAME
FROM SYS.DEFAULT_CONSTRAINTS
WHERE OBJECT_NAME(PARENT_OBJECT_ID) = '<Table_Name>')
SET @sql = N'ALTER TABLE <Table_Name> DROP CONSTRAINT ' + @ConstraintName
EXEC sp_executesql @sql
ALTER TABLE <Table_Name> DROP COLUMN <Column_Name>
Cheers friends...:)
If a default constraint is applied on more then one column, then how can we make sure that only the required column's default constraint will get deleted.
ReplyDelete