Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a default value to an already existing column?

I have an existing column in my SQL Server database. I have tried about everything I can think of but can not get a default value to be added to the column. What works in every other database is

alter table mytable    alter column mycolumn set default(now()) --mycolumn is a datetime 

How do I do this in SQL Server?

The error I get for that exact syntax is incorrect syntax near the keyword 'set'

like image 718
Earlz Avatar asked Jun 17 '10 00:06

Earlz


People also ask

Which keyword is used to add default value to a column?

When bound to a column, a default value is inserted when: A value isn't explicitly inserted. Either the DEFAULT VALUES or DEFAULT keywords are used with INSERT to insert default values.


2 Answers

Use:

ALTER TABLE dbo.mytable ADD CONSTRAINT def_mycolumn DEFAULT GETDATE() FOR mycolumn 

For more info, see: Working with Default Constraints

like image 89
OMG Ponies Avatar answered Oct 06 '22 11:10

OMG Ponies


If you want to change the default value of an already existing column. You need to first drop the constraint and then add the constraint all over again as below

ALTER TABLE <TABLE>  DROP CONSTRAINT <CONSTRAINT NAME>  ALTER TABLE <TABLE>  ADD CONSTRAINT <CONSTRAINT NAME> DEFAULT <VALUE> for <COLUMN> 

If you are not having the Constraint details of the table, you can use the below query

sp_helpconstraint <TABLE> 
like image 45
suryakiran Avatar answered Oct 06 '22 10:10

suryakiran