简体   繁体   中英

Adding new NOT NULL column to existing database

Lets say I have a system that has a person table:

CREATE TABLE Person
(
    FirstName NVARCHAR(50) NOT NULL,
    LastName  NVARCHAR(50) NOT NULL,
    DOB       DATE NOT NULL
)

If we want to update the system after it has been in place for a number of years and we now want to also capture the person's address (by means of a new NVARCHAR column called Address which is NOT NULL )

Therefore we want all new records to be NOT NULL but we don't have any data for the old records so they would have to be NULL

What is the best way to do this? We cannot add a NOT NULL column because it would be NULL for all the existing records.

Is the best way to add the column and allow NULLS, add some placeholder value (EG '.') to the existing records, then alter the column to be NULL?

Or is there some other way to do it?

You cannot add a new NOT NULL column without assigning non-NULL values to existing rows (via a default constraint). However, you can add a NULL column and ensure only NOT NULL values going forward by specifying a check constraint that prohibits NULL values along with the NOCKECK option so that existing data are not validated:

CREATE TABLE dbo.Person
(
    FirstName NVARCHAR(50) NOT NULL,
    LastName  NVARCHAR(50) NOT NULL,
    DOB       DATE NOT NULL
)
INSERT INTO dbo.Person (FirstName, LastName , DOB)
    VALUES(N'foo', N'bar', '20010101');
GO
--add new column and CHECK constraint with NOCHECK
ALTER TABLE dbo.Person WITH NOCHECK
    ADD Address nvarchar(50) NULL
    CONSTRAINT CK_Person_Address CHECK (Address IS NOT NULL);
GO
--this fails due to check constraint violation
INSERT INTO dbo.Person (FirstName, LastName , DOB)
    VALUES(N'foo2', N'bar2', '20020101');
GO
--this succeeds
INSERT INTO dbo.Person (FirstName, LastName , DOB, Address)
    VALUES(N'foo2', N'bar2', '20020101', N'non-null address');
GO

This method provides the proper NULL semantics for existing persons that have no addresses yet guarantee the desired data integrity for new persons.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM