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

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

    Well, I now have some modification to my previous answer. I have noticed that none of the answers mentioned IF NOT EXISTS. So I am going to provide a new solution of it as I have faced some problems altering the table.

    IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.columns WHERE table_name = 'TaskSheet' AND column_name = 'IsBilledToClient')
    BEGIN
    ALTER TABLE dbo.TaskSheet ADD
     IsBilledToClient bit NOT NULL DEFAULT ((1))
    END
    GO
    

    Here TaskSheet is the particular table name and IsBilledToClient is the new column which you are going to insert and 1 the default value. That means in the new column what will be the value of the existing rows, therefore one will be set automatically there. However, you can change as you wish with the respect of the column type like I have used BIT, so I put in default value 1.

    I suggest the above system, because I have faced a problem. So what is the problem? The problem is, if the IsBilledToClient column does exists in the table table then if you execute only the portion of the code given below you will see an error in the SQL server Query builder. But if it does not exist then for the first time there will be no error when executing.

    ALTER TABLE {TABLENAME}
    ADD {COLUMNNAME} {TYPE} {NULL|NOT NULL}
    CONSTRAINT {CONSTRAINT_NAME} DEFAULT {DEFAULT_VALUE}
    [WITH VALUES]
    

提交回复
热议问题