在sql中,两列不能同时为null

时间:2013-10-03 09:39:12

标签: sql

假设有一个名为

的表

员工

ID number, name varchar(24 char), address varchar2(100 char), alternateAddress(100 char), sex varchar2(10 char)

现在我想放置约束,使地址和alternateAddress都不能为空,即 可能的情况是:

  • address为null且alternateAddress不为null
  • alternateAddress为空且地址不为空
  • alternateAddress不为null且地址不为空

但不能发生Employee表中的任何记录与alternateAddress一起插入并且地址都为null

4 个答案:

答案 0 :(得分:7)

为您的表创建一个约束,如下所示:

ALTER TABLE [dbo].[Employee]  WITH CHECK ADD  CONSTRAINT [CK_OneAddress] CHECK  ((NOT [address] IS NULL) OR (NOT [alternateAddress] IS NULL))
GO

ALTER TABLE [dbo].[Employee] CHECK CONSTRAINT [CK_OneAddress]
GO

答案 1 :(得分:2)

像这样创建约束:

(address is null and alternateAddress is not null) or 
(alternateAddress is null and address is not null) or 
(alternateAddress is not null and address is not null)

答案 2 :(得分:0)

因此,根据德摩根定律,(A和B)不等于(不是A或不是B)

(address is not null OR alternateAddress is not null)

答案 3 :(得分:0)

您不能使用:

IF(COALESCE(address, alternateAddress) IS NOT NULL)

WHERE (COALESCE(address, alternateAddress) IS NOT NULL)

那是不好的形式吗?