Thursday, December 20, 2012

t-sql change a column from nullable to not null and add default value it


--1.make sure all records have a value in the column
update [TableName]
SET [ColumnName] = [Default Value]

--2. change the column to not null
ALTER TABLE [TableName]
ALTER COLUMN [ColumnName] [data type] NOT NULL
GO

--3. add default value constraint to the column
ALTER TABLE [TableName] WITH NOCHECKADD CONSTRAINT [DF_DefaultName] DEFAULT [Default Value] FOR [ColumnName]
GO

No comments: