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
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.