Sunday, March 25, 2012

changing the default value for a column

Does anybody know how I can change the default value for a column?
I was trying to remove the default value in order to add the new one
afterwards. This is what I tried:

alter table /table-name/ drop default for /column-name/
alter table /table-name/ alter column /column-name/
(/new-decl-without-default/)

It did not work. I cannot find a solution in the documentation. Maybe
you can help me out?

Thank you,
JohanALTER TABLE table_name
DROP CONSTRAINT name_of_default_constraint

ALTER TABLE table_name
ADD CONSTRAINT name_of_default_constraint DEFAULT 123 FOR column_name
--
David Portas
SQL Server MVP
--|||David Portas schreef:
> ALTER TABLE table_name
> DROP CONSTRAINT name_of_default_constraint

Thank you for the quick reply. But how do I know the
name_of_default_constraint? I created the default value like this:

alter table /table_name/ add default /default_value/ for /column_name/

Johan|||It's a good idea to give constraints meaningful names when you create
them, otherwise the server assigns them an obscure unique identifier
name. Use a consistent naming convention and then you'll know the
constraint names for tables and columns.

You can find the name of an existing default using the Object Browser
in Query Analyzer or in the output of sp_help 'table_name'
--
David Portas
SQL Server MVP
--|||Hi,

something like this could meet your requirements:

declare @.myStatement nvarchar(4000)

select @.myStatement=('ALTER TABLE RP_CUSTOM_ATTRIBUTE DROP CONSTRAINT ' +
(select so.name
from sysobjects so, syscolumns sc
where sc.name = 'YOUR_COLUMN_NAME' and sc.cdefault = so.id))

EXEC sp_executesql @.myStatement
go

Karsten

"Johan Vervloet" <johanv@.chiro.be> schrieb im Newsbeitrag
news:41fe1db7$0$28977$e4fe514c@.news.xs4all.nl...
> David Portas schreef:
> > ALTER TABLE table_name
> > DROP CONSTRAINT name_of_default_constraint
> Thank you for the quick reply. But how do I know the
> name_of_default_constraint? I created the default value like this:
> alter table /table_name/ add default /default_value/ for /column_name/
> Johan

No comments:

Post a Comment