views:

91

answers:

3

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?

+1  A: 

Its a default constraint, you need to perform a:

ALTER TABLE
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.

Dan Rigby
A: 

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)

Yishai
Yeah, that becomes an issue for any large scale database roll out. What you end up having to do is force yourself to always name your constraints so that they're consistent across environments.Ex.: ALTER table sometable Add somecolumn nchar(1) NOT NULL CONSTRAINT DF_TableName_SomeColumn DEFAULT 'N'
Dan Rigby