How can I add a column with a default value to an existing table in SQL Server 2000 / SQL Server 2005?
Example:
ALTER TABLE tes
ADD ssd NUMBER DEFAULT '0';
ALTER TABLE ADD ColumnName {Column_Type} Constraint
The MSDN article ALTER TABLE (Transact-SQL) has all of the alter table syntax.
You can do the thing with T-SQL in the following way.
ALTER TABLE {TABLENAME}
ADD {COLUMNNAME} {TYPE} {NULL|NOT NULL}
CONSTRAINT {CONSTRAINT_NAME} DEFAULT {DEFAULT_VALUE}
As well as you can use SQL Server Management Studio also by right clicking table in the Design menu, setting the default value to table.
And furthermore, if you want to add the same column (if it does not exists) to all tables in database, then use:
USE AdventureWorks;
EXEC sp_msforeachtable
'PRINT ''ALTER TABLE ? ADD Date_Created DATETIME DEFAULT GETDATE();''' ;
ALTER TABLE tbl_table ADD int_column int NOT NULL DEFAULT(0)
From this query you can add a column of datatype integer with default value 0.
Beware when the column you are adding has a NOT NULL
constraint, yet does not have a DEFAULT
constraint (value). The ALTER TABLE
statement will fail in that case if the table has any rows in it. The solution is to either remove the NOT NULL
constraint from the new column, or provide a DEFAULT
constraint for it.
If you want to add multiple columns you can do it this way for example:
ALTER TABLE YourTable
ADD Column1 INT NOT NULL DEFAULT 0,
Column2 INT NOT NULL DEFAULT 1,
Column3 VARCHAR(50) DEFAULT 'Hello'
GO