Add a column with a default value to an existing table in SQL Server

后端 未结 30 2594
轮回少年
轮回少年 2020-11-22 12:00

How can I add a column with a default value to an existing table in SQL Server 2000 / SQL Server 2005?

30条回答
  •  春和景丽
    2020-11-22 12:11

    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();''' ;
    

提交回复
热议问题