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

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

    This can be done in the SSMS GUI as well. I show a default date below but the default value can be whatever, of course.

    1. Put your table in design view (Right click on the table in object explorer->Design)
    2. Add a column to the table (or click on the column you want to update if it already exists)
    3. In Column Properties below, enter (getdate()) or 'abc' or 0 or whatever value you want in Default Value or Binding field as pictured below:

    0 讨论(0)
  • 2020-11-22 12:25
    ALTER TABLE MYTABLE ADD MYNEWCOLUMN VARCHAR(200) DEFAULT 'SNUGGLES'
    
    0 讨论(0)
  • 2020-11-22 12:28

    Use:

    ALTER TABLE {TABLENAME} 
    ADD {COLUMNNAME} {TYPE} {NULL|NOT NULL} 
    CONSTRAINT {CONSTRAINT_NAME} DEFAULT {DEFAULT_VALUE}
    

    Reference: ALTER TABLE (Transact-SQL) (MSDN)

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

    Try this

    ALTER TABLE Product
    ADD ProductID INT NOT NULL DEFAULT(1)
    GO
    
    0 讨论(0)
  • 2020-11-22 12:28
    IF NOT EXISTS (
        SELECT * FROM INFORMATION_SCHEMA.COLUMNS
        WHERE TABLE_NAME ='TABLENAME' AND COLUMN_NAME = 'COLUMNNAME'
    )
    BEGIN
        ALTER TABLE TABLENAME ADD COLUMNNAME Nvarchar(MAX) Not Null default
    END
    
    0 讨论(0)
  • 2020-11-22 12:29

    Use:

    -- Add a column with a default DateTime  
    -- to capture when each record is added.
    
    ALTER TABLE myTableName  
    ADD RecordAddedDate SMALLDATETIME NULL DEFAULT (GETDATE())  
    GO 
    
    0 讨论(0)
提交回复
热议问题