Check if all three columns are either not null or null
Asked Answered
A

2

8

I have a table with 4 columns:

create table dbo.Table ( 
  Id int not null,
  A int null,
  B int null,   
  C nvarchar (4000) null
)

How can I make sure that A, B and C are all three null or all three not null?

Amphiaster answered 24/4, 2015 at 11:34 Comment(0)
J
13

You can set a check constraint:

constraint [check_abc] check ( ([A] is null and [B] is null and [C] is null) or
                               ([A] is not null and [B] is not null and [C] is not null) )
Jannette answered 24/4, 2015 at 11:36 Comment(0)
A
1

You might also consider factoring these related columns out to a second table in which they are declared not null and only inserting a row where they apply.

create table dbo.Table1( 
  Id int not null primary key
)


create table dbo.Table2( 
  Id int not null primary key references Table1,
  A int not null,
  B int not null,   
  C nvarchar (4000) not null
)
Abernon answered 25/4, 2015 at 11:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.