SQL: Allow NULL on two columns but not both

2020-07-18 11:44发布

I have a table that is simply a lookup with two columns.

spiceId - INT
spiceDes - VARCHAR(100)

Now, I have the columns set as allow NULL for both columns, but I would like to add a constraint where it should be that only one column could be NULL for any record. That is spiceID and spiceDes could not, both be NULL.

How can I add this constraint?

2条回答
劫难
2楼-- · 2020-07-18 11:50

Use Alter table to add a check constraint on your table:

ALTER TABLE tableName
ADD  CONSTRAINT CK_nulltest
CHECK (spiceId IS NOT NULL OR spiceDes IS NOT NULL);
查看更多
▲ chillily
3楼-- · 2020-07-18 12:01

What about CHECK Constraints?

ADD CONSTRAINT chkIsNotNull CHECK (spiceId is not null or spiceDes is not null);
查看更多
登录 后发表回答