Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you drop a default value from a column in a table?

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?

like image 923
Yishai Avatar asked Sep 01 '09 20:09

Yishai


People also ask

How do I drop a default value in a column in SQL?

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.

How do I change the default value of a column in a table?

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.

Which constraint removes default value of a column?

The DROP DEFAULT command is used to delete a DEFAULT constraint.


2 Answers

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.

like image 72
Dan Rigby Avatar answered Oct 16 '22 14:10

Dan Rigby


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)

like image 34
Yishai Avatar answered Oct 16 '22 13:10

Yishai