Tuesday, February 24, 2015

T-SQL update script to bolt on a new and not null column onto a table

IF EXISTS(SELECT * FROM sys.columns WHERE [name] = N'IsCorny'
      AND [object_id] = OBJECT_ID(N'Users'))
   BEGIN
      PRINT 'There is already a IsCorny flag.'
   END
ELSE
   BEGIN
      DECLARE @nullrecordcount int
      SELECT @nullrecordcount=COUNT(Id) FROM Users
      IF @nullrecordcount > 0
         ALTER Table Users
         Add IsCorny bit
      ELSE
         ALTER Table Users
         Add IsCorny bit NOT NULL
      ALTER TABLE Users
      ADD CONSTRAINT IsCorny_Constraint
      DEFAULT 0 FOR IsCorny
   END
GO
DECLARE @nullrecordcount int
SELECT @nullrecordcount=COUNT(Id) FROM Users WHERE IsCorny is null
IF @nullrecordcount > 0
   BEGIN
      UPDATE Users SET IsCorny=0 WHERE 1=1
      ALTER TABLE Users
      ALTER Column IsCorny bit NOT NULL
   END
ELSE
   BEGIN
      PRINT 'An attempt to make IsCorny not nullable will not be undertaken.'
   END

No comments:

Post a Comment