I have a number of columns in my database that were originally created as smalldatetime
and that really need to be datetime
. Many of these columns were created with the DDL:
[columnname] smalldatetime not null default getdate()
...which means that in order to alter the column's type, I first have to drop the default, and then re-create the default after altering it.
Of course, I didn't specify a name for the default in the DDL, so the columns all have defaults with names like DF__CaseLock__CaseCo__182C9B23
. And when my application creates its database, it does so by executing a script, so the names of the defaults in my customers' databases are (I'm guessing; I haven't verified this) different from their names in mine.
And even if I know the name of the default constraint, I can't figure out the syntax for adding it back in after I drop it. In fact, it's not clear to me that it's possible to add a default constraint to an existing column.
It appears that what I have to do is something like this:
declare @t table (id int not null primary key, date smalldatetime null)
insert into @t (id, date)
select id, date_column from my_table
drop constraint constraint_name
alter table my_table drop column date_column;
alter table my_table add date_column datetime default getdate()
update my_table set date_column = t.date FROM my_table m JOIN @t t ON m.id = t.ID
...only I can only write that script if I know what constraint_name
is, because I can't drop a column that's referenced in a constraint.
Is this really that hard?