SQL Server – Enforce NULL Constraint on one column out of Two in a Table

Column 1 has data Column 2 should be NULL

Column 2 has data Column 1 should be NULL

that means only one column should be NULL at a time.

Here is SQL query

ALTER TABLE [dbo].[TableName] WITH CHECK ADD CONSTRAINT [CHK_TableName_OneColNotNull] CHECK (([Col1] IS NULL AND [Col2] IS NOT NULL OR [Col1] IS NOT NULL AND [Col2] IS NULL))
GO

Advertisements