Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to modify datatype of a column with a default value

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
like image 498
GregM Avatar asked Feb 15 '12 19:02

GregM


2 Answers

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
like image 174
marc_s Avatar answered Nov 09 '22 09:11

marc_s


You could do it as a three step process

  • add the new column with a different name,
  • copy the values from the old column to the new
  • drop the old column

It it matters that the name is the same, then repeat the process to change the name back.

like image 2
Matt T Avatar answered Nov 09 '22 09:11

Matt T