How do you alter a column to remove the default value?
The column was created with:
ALTER table sometable Add somecolumn nchar(1) NOT NULL DEFAULT 'N'
And then altered with:
alter table sometable alter column somecolumn nchar(1) null
That allows nulls, but the default value remains. How can you remove it?
Before dropping a default, unbind the default by executing sp_unbindefault if the default is currently bound to a column or an alias data type. After a default is dropped from a column that allows for null values, NULL is inserted in that position when rows are added and no value is explicitly supplied.
Changing a Column's Default Value. To set a new default for a column, use a command like: ALTER TABLE products ALTER COLUMN price SET DEFAULT 7.77; Note that this doesn't affect any existing rows in the table, it just changes the default for future INSERT commands.
The DROP DEFAULT command is used to delete a DEFAULT constraint.
Its a default constraint, you need to perform a:
ALTER TABLE {TableName} DROP CONSTRAINT ConstraintName
If you didn't specify a name when you created the constraint, then SQL Server created one for you. You can use SQL Server Management Studio to find the constraint name by browsing to the table, opening its tree node, then opening the Constraints node.
If I remember correctly, the constraint will be named something along the lines of DF_SomeStuff_ColumnName.
EDIT: Josh W.'s answer contains a link to a SO question that shows you how to find the auto generated constraint name using SQL instead of using the Management Studio interface.
This is what I came up with (before seeing Josh W. answer, well actually I saw it but skimmed it so fast I misunderstood it):
declare @name nvarchar(100) select @name = [name] from sys.objects where type = 'D' and parent_object_id = object_id('sometable') if (@name is not null) begin exec ('alter table [sometable] drop constraint [' + @name +']') end
The advantage I have here is that I know that there is only one such constraint on the whole table. If there had been two, well I guess that is why you are supposed to name them ;).
(The issues is that that this is a modification made to 10 different customer databases, so there isn't one consistent name to put in a script)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With