How to modify datatype of a column with a default value

GregM picture GregM · Feb 15, 2012 · Viewed 35.4k times · Source

I'm trying to change the datatype of a column in SQL Server from tinyint to smallint.

But there's a default value on my column and I don't know the name of the constraint.

Is there an easy way to do it ?

This don't work because of the default constraint :

ALTER TABLE mytable
Alter Column myColumn smallint NOT NULL default 1

Answer

marc_s picture marc_s · Feb 15, 2012

You need to do this in several steps - first: drop the default constraint on your column, then modify your column.

You could use code something like this:

-- find out the name of your default constraint - 
-- assuming this is the only default constraint on your table
DECLARE @defaultconstraint sysname

SELECT @defaultconstraint = NAME 
FROM sys.default_constraints 
WHERE parent_object_id = object_ID('dbo.mytable')

-- declare a "DROP" statement to drop that default constraint
DECLARE @DropStmt NVARCHAR(500)

SET @DropStmt = 'ALTER TABLE dbo.mytable DROP CONSTRAINT ' + @defaultconstraint

-- drop the constraint
EXEC(@DropStmt)

-- alternatively: if you *know* the name of the default constraint - you can do this
-- more easily just by executing this single line of T-SQL code:

-- ALTER TABLE dbo.mytable DROP CONSTRAINT (fill in name of constraint here)

-- modify the column's datatype        
ALTER TABLE dbo.mytable
Alter Column myColumn smallint NOT NULL 

-- re-apply a default constraint - hint: give it a sensible name!
ALTER TABLE dbo.mytable
ADD CONSTRAINT DF_mytable_myColumn DEFAULT 1 FOR MyColumn