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

后端 未结 30 2175
轮回少年
轮回少年 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:08

    Example:

    ALTER TABLE tes 
    ADD ssd  NUMBER   DEFAULT '0';
    
    0 讨论(0)
  • 2020-11-22 12:10
    ALTER TABLE ADD ColumnName {Column_Type} Constraint
    

    The MSDN article ALTER TABLE (Transact-SQL) has all of the alter table syntax.

    0 讨论(0)
  • 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();''' ;
    
    0 讨论(0)
  • 2020-11-22 12:11
    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.

    0 讨论(0)
  • 2020-11-22 12:13

    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.

    0 讨论(0)
  • 2020-11-22 12:14

    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
    
    0 讨论(0)
提交回复
热议问题