I know you can change the default value of an existing column like this:
ALTER TABLE Employee ADD CONSTRAINT DF_SomeName DEFAULT N'SANDNES' FOR CityBorn;
But according to this my query supposed to work:
ALTER TABLE MyTable ALTER COLUMN CreateDate DATETIME NOT NULL
CONSTRAINT DF_Constraint DEFAULT GetDate()
So here I'm trying to make my column Not Null and also set the Default value. But getting Incoorect Syntax Error near CONSTRAINT. Am I missing sth?
Best Answer
I think issue here is with the confusion between
Create Table
andAlter Table
commands. If we look atCreate table
then we can add a default value and default constraint at same time as:you can check for complete definition here: http://msdn.microsoft.com/en-IN/library/ms174979.aspx
but if we look at the
Alter Table
definition then withALTER TABLE ALTER COLUMN
you cannot addCONSTRAINT
the options available forADD
are:Check here: http://msdn.microsoft.com/en-in/library/ms190273.aspx
So you will have to write two different statements one for Altering column as:
and another for altering table and add a default constraint
ALTER TABLE MyTable ADD CONSTRAINT DF_Constraint DEFAULT GetDate() FOR CreateDate;
Hope this helps!!!