NOT NULL is integrity constraint
NOT NULL constraints in
Microsoft SQL Server allow you to specify that a column may not contain NULL values.
By default, a table
column can hold NULL values.
USE AdventureWorksGO
-- NOT NULL Constraint when Table is created
CREATE TABLE ConstraintTable
(ID INT, ColSecond INT NOT NULL)
-- NOT NULL Constraint when Table is created
CREATE TABLE ConstraintTable
(ID INT, ColSecond INT NOT NULL)
GO
--
NOT NULL Constraint after Table is created
ALTER TABLE ConstraintTable
ALTER COLUMN ID INT NOT NULL
ALTER TABLE ConstraintTable
ALTER COLUMN ID INT NOT NULL
GO
SQL Server checks the
column’s current contents for any NULL values. If the column currently contains
NULL values, the constraint creation fails.
You will have to do it
in two steps:
1.
Update the table so that
there are no nulls in the column.
UPDATE
MyTable SET MyNullableColumn = 0 WHERE MyNullableColumn IS NULL
2.
Alter the table to
change the property of the column
ALTER
TABLE MyTable
ALTER
COLUMN MyNullableColumn Datatype NOT NULL
No comments:
Post a Comment