patternsqlCritical
Check constraint only one of three columns is non-null
Viewed 0 times
threecolumnsnonnulloneconstraintcheckonly
Problem
I have a (SQL Server) table that contains 3 types of results: FLOAT, NVARCHAR(30), or DATETIME (3 separate columns). I want to ensure that for any given row, only one column has a result and the other columns are NULL. What is the simplest check constraint to achieve this?
The context for this is trying to retrofit the ability to capture non-numeric results into an existing system. Adding two new columns to the table with a constraint to prevent more than one result per row was the most economical approach, not necessarily the correct one.
Update: Sorry, data type snafu. Sadly I wasn't intending the result types indicated to be interpreted as SQL Server datatypes, just generic terms, fixed now.
The context for this is trying to retrofit the ability to capture non-numeric results into an existing system. Adding two new columns to the table with a constraint to prevent more than one result per row was the most economical approach, not necessarily the correct one.
Update: Sorry, data type snafu. Sadly I wasn't intending the result types indicated to be interpreted as SQL Server datatypes, just generic terms, fixed now.
Solution
The following should do the trick:
CREATE TABLE MyTable (col1 FLOAT NULL, col2 NVARCHAR(30) NULL, col3 DATETIME NULL);
GO
ALTER TABLE MyTable
ADD CONSTRAINT CheckOnlyOneColumnIsNull
CHECK
(
( CASE WHEN col1 IS NULL THEN 0 ELSE 1 END
+ CASE WHEN col2 IS NULL THEN 0 ELSE 1 END
+ CASE WHEN col3 IS NULL THEN 0 ELSE 1 END
) = 1
)
GOCode Snippets
CREATE TABLE MyTable (col1 FLOAT NULL, col2 NVARCHAR(30) NULL, col3 DATETIME NULL);
GO
ALTER TABLE MyTable
ADD CONSTRAINT CheckOnlyOneColumnIsNull
CHECK
(
( CASE WHEN col1 IS NULL THEN 0 ELSE 1 END
+ CASE WHEN col2 IS NULL THEN 0 ELSE 1 END
+ CASE WHEN col3 IS NULL THEN 0 ELSE 1 END
) = 1
)
GOContext
StackExchange Database Administrators Q#5278, answer score: 101
Revisions (0)
No revisions yet.