Alter column default value
There is no direct way to change default value of a column in SQL server, but the following parameterized script will do the work:
DECLARE @table NVARCHAR(100);
DECLARE @column NVARCHAR(100);
DECLARE @newDefault NVARCHAR(100);
SET @table = N'TableName';
SET @column = N'ColumnName';
SET @newDefault = N'0';
IF EXISTS (
SELECT name
FROM sys.default_constraints
WHERE parent_object_id = OBJECT_ID(@table)
AND parent_column_id = COLUMNPROPERTY(OBJECT_ID(@table), @column, 'ColumnId')
)
BEGIN
DECLARE @constraintName AS NVARCHAR(200);
DECLARE @constraintQuery AS NVARCHAR(2000);
SELECT @constraintName = name
FROM sys.default_constraints
WHERE parent_object_id = OBJECT_ID(@table)
AND parent_column_id = COLUMNPROPERTY(OBJECT_ID(@table), @column, 'ColumnId');
SET @constraintQuery = N'ALTER TABLE ' + @table + N' DROP CONSTRAINT '
+ @constraintName + N'; ALTER TABLE ' + @table + N' ADD CONSTRAINT '
+ @constraintName + N' DEFAULT ' + @newDefault + N' FOR ' + @column;
EXECUTE sp_executesql @constraintQuery;
END;
Just fill the parameters and execute. The script removes existing constraint and creates a new one with designated default value.
For altering an existing column you need to:
ALTER TABLE MyTable ALTER COLUMN CreateDate DATETIME NOT NULL;
ALTER TABLE MyTable ADD CONSTRAINT DF_Constraint DEFAULT GetDate() FOR CreateDate;
I think issue here is with the confusion between Create Table
and Alter Table
commands.
If we look at Create table
then we can add a default value and default constraint at same time as:
<column_definition> ::=
column_name <data_type>
[ FILESTREAM ]
[ COLLATE collation_name ]
[ SPARSE ]
[ NULL | NOT NULL ]
[
[ CONSTRAINT constraint_name ] DEFAULT constant_expression ]
| [ IDENTITY [ ( seed,increment ) ] [ NOT FOR REPLICATION ]
]
[ ROWGUIDCOL ]
[ <column_constraint> [ ...n ] ]
[ <column_index> ]
ex:
CREATE TABLE dbo.Employee
(
CreateDate datetime NOT NULL
CONSTRAINT DF_Constraint DEFAULT (getdate())
)
ON PRIMARY;
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 with ALTER TABLE ALTER COLUMN
you cannot add
CONSTRAINT
the options available for ADD
are:
| ADD
{
<column_definition>
| <computed_column_definition>
| <table_constraint>
| <column_set_definition>
} [ ,...n ]
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:
ALTER TABLE MyTable ALTER COLUMN CreateDate DATETIME NOT NULL;
and another for altering table and add a default constraint
ALTER TABLE MyTable ADD CONSTRAINT DF_Constraint DEFAULT GetDate() FOR CreateDate;
Hope this helps!!!