Alter Table Script

-- Set all existing NULL value to 0
UPDATE t SET t.Col01 = 0 FROM tbTable01 t WHERE t.Col01 IS NULL

-- Make column NOT NULL
ALTER TABLE tbTable01 ALTER COLUMN Col01 TINYINT NOT NULL;

-- ADD Default Constraint of 0
ALTER TABLE tbTable01 ADD CONSTRAINT [DF_tbTable01_Col01] DEFAULT ((0)) FOR Col01
-- Add column NOT NULL
-- ADD Default Constraint of 0
ALTER TABLE tbTable01 ADD Col01 TINYINT NOT NULL CONSTRAINT [DF_tbTable01_Col01] DEFAULT ((0));

Create Table Script

CREATE TABLE tbTable01(
[Col01] [TINYINT] NOT NULL CONSTRAINT DF_tbTable01_Col01 DEFAULT 0,
[Col02] [DATETIME] NOT NULL CONSTRAINT [DF_tbTable01_Col02] DEFAULT (GETDATE())
[Col03] [DATETIME2] NOT NULL CONSTRAINT [DF_tbTable01_Col03] DEFAULT (SYSDATETIME())
[Col04] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL DEFAULT ('')
[Col05] [bit] NOT NULL DEFAULT ((0))

Alter Table Script

ALTER TABLE [DBO].[tblTable01] ADD  CONSTRAINT [DF_tblTable01_IPAddress]  DEFAULT ('0.0.0.0') FOR [IPAddress]
GO

ALTER TABLE [DBO].[tblTable01] ADD  CONSTRAINT [DF_DBO_tblTable01_IsActive]  DEFAULT ((1)) FOR [IsActive]
GO

ALTER TABLE [DBO].[tblTable01] ADD  CONSTRAINT [DF_DBO_tblTable01_UTCDateCreated]  DEFAULT (getutcdate()) FOR [UTCDateCreated]
GO
-- If column does not exist.
ALTER TABLE tbTemp ADD bActive BIT CONSTRAINT DF_tbTemp_bActive DEFAULT 0 WITH VALUES;

-- If column already exist.
ALTER TABLE [DBO].[tbTemp] ADD CONSTRAINT [DF_tbTemp_bActive]  DEFAULT (0) FOR [bActive]
GO
Last modified: October 15, 2020

Author

Comments

Write a Reply or Comment