7

假设有一个表叫

员工

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

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

  • 地址为空且alternateAddress 不为空
  • alterAddress 为空且地址不为空
  • AlternateAddress 不为空且地址不为空

但是不会发生 Employee 表中的任何记录都插入了 alternateAddress 和 address 两者都为空

4

4 回答 4

8

像这样为您的表创建一个约束:

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
于 2013-10-03T09:45:19.207 回答
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)
于 2013-10-03T09:40:59.833 回答
0

根据德摩根定律,not (A and B) 等价于 (not A or not B),因此

(address is not null OR alternateAddress is not null)
于 2018-07-24T22:05:10.823 回答
0

你可以不使用:

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

或者

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

还是那是不好的形式?

于 2018-07-24T22:13:14.627 回答