Adding a NOT NULL constraint to a column

When you add a NOT NULL constraint to a column storing NULL entries without specifying a default value, the deployment process may fail because the new constraint conflicts with the existing NULL values in the column.

Solution: Instead, you need to create a migration script to update all existing NULL entries of the column with a NOT NULL value:

  • Create a migration script to update NULL values and execute it
  • Add a NOT NULL constraint

Note

The comparison engine of the tools doesn’t handle all cases automatically, which is why the cases mentioned above must be resolved manually.

The screenshot displays the Schema Comparison document and the scripts generated by Schema Compare Engine and a migration script, which should be created manually to perform errorless data migration.

Scripts

The table provides source and target table script examples to illustrate the case:

Source table script example Target table script example
CREATE TABLE [dbo].[Product](
 [ProductID][INT] IDENTITY PRIMARY KEY,
 [ProductNumber] [INT] NOT NULL,
 [ProductName] [NVARCHAR](25) NULL
)
GO
CREATE TABLE [dbo].[Product](
[ProductID] [INT] IDENTITY PRIMARY KEY,
[ProductNumber] [INT] NULL,
[ProductName] [NVARCHAR](25) NULL
)
GO
 
INSERT INTO [dbo].[Product]([ProductNumber], [ProductName])
    VALUES (1125, 'screwriver');
INSERT INTO [dbo].[Product]([ProductNumber], [ProductName])
    VALUES (1126, NULL);
GO

The table provides examples of scripts generated by the Schema Comparison engine and those that should be generated manually for errorless data migration to illustrate the case:

Script generated by the Schema Comparison engine Script that should be generated manually for errorless data migration
ALTER TABLE [dbo].[Product]
    ALTER COLUMN [ProductNumber] [INT] NOT NULL
GO
-- migration script:
 
UPDATE [dbo].[Product]
SET [ProductNumber] = < default_value >
WHERE [ProductNumber] IS NULL
GO
 
-- migration script.
 
ALTER TABLE [dbo].[Product]
ALTER COLUMN [ProductNumber] [INT] NOT NULL
GO

Want to Find out More?

Overview

Overview

Take a quick tour to learn all about the key benefits delivered by dbForge Schema Compare for SQL Server.
All Features

All features

Get acquainted with the rich features and capabilities of the Schema Compare in less than 5 minutes.
Request a demo

Request a demo

If you consider employing the Schema Compare for your business, request a demo to see it in action.
Ready to start using dbForge Schema Compare for SQL Server?