Test Column exists, Add Column, and Update Column

前端 未结 5 1698
一整个雨季
一整个雨季 2020-12-28 13:03

I\'m trying to write a SQL Server database update script. I want to test for the existence of a column in a table, then if it doesn\'t exist add the column with a default va

5条回答
  •  孤城傲影
    2020-12-28 13:43

    If you're using at least SQL Server 2008, you can specify WITH VALUES at the time of column addition, which will populate existing records with the default value for that attribute.

    IF COL_LENGTH('[dbo].[Trucks]', 'Is4WheelDrive') IS NULL
    BEGIN
    
        ALTER TABLE [dbo].[Trucks]
        ADD [Is4WheelDrive] BIT NULL DEFAULT 1
        WITH VALUES;
    
    END
    

    This will add a new column, [Is4WheelDrive], to the table [dbo].[Trucks] if that column doesn't exist. The new column, if added, will populate existing records with the default value, which in this case is a BIT value of 1. If the column already existed, no records would be modified.

提交回复
热议问题