Tsql 指定一个约束,当另一列不为null时,该约束防止这两列中的任何一列为null?
假设我想在一个表中存储一个间隔,其中间隔可以指定为单个日期,也可以指定为一个范围,因此,字段应该是:Tsql 指定一个约束,当另一列不为null时,该约束防止这两列中的任何一列为null?,tsql,constraints,Tsql,Constraints,假设我想在一个表中存储一个间隔,其中间隔可以指定为单个日期,也可以指定为一个范围,因此,字段应该是: | id | since | until | at_date | 现在,我希望像since is null and until is not null或since is not null and until is null这样的情况永远不会发生,但是since is null and until is null和since is not null and until is not null都是
| id | since | until | at_date |
现在,我希望像since is null and until is not null
或since is not null and until is null
这样的情况永远不会发生,但是since is null and until is null
和since is not null and until is not null
都是可以的(但是,如果指定了在
日期的话,第一种情况才可以)
也许将和合并到一列中是有意义的,但在我的情况下,有时只选择一列或另一列是有意义的,所以我认为将它们分开是可以的
编辑:
创建表格菜单\u可用性
(菜单id int不为空,
每日服务开始时间为空,
每日服务结束时间为空,
每周服务关闭tinyint空,
一次性服务关闭日期为空,
约束CHU有效周日
检查((每周服务关闭为空)
或(每周服务关闭=0)),
约束CHU非空计划
检查((每日服务开始不为空,每日服务结束不为空)
或(每日服务开始为空,每日服务结束为空),
约束设置为“周”或“时间”
检查(每日服务开始时间不为空
或每周服务关闭不为空
或一次性服务关闭不为空),
仅限一周或一次
检查((每周服务关闭为空,一次服务关闭不为空)
或者(每周服务关闭不为空,一次服务关闭为空)
这就是我目前所拥有的。。。但是它真的很乱…我认为你应该在日期删除,并且只在你所有的时间间隔使用,因为和直到
将设置为非包容性,以便在中的日期中存储的值为“2013-03-01”,如下所示
since until
2013-03-01 2013-03-02
更新:
可以使用不允许为null的case语句创建持久化计算位列
create table YourTable
(
id int identity primary key,
since datetime,
until datetime,
at_date datetime,
sn as case when since is null and until is null or
since is not null and until is not null then cast(1 as bit)
end persisted not null
)
或具有检查约束
create table T
(
id int identity primary key,
since datetime,
until datetime,
at_date datetime,
constraint ch_sn check(since is null and until is null or
since is not null and until is not null)
)
@wvxvw它是文档的一部分。请参阅“计算列表达式”
create table T
(
id int identity primary key,
since datetime,
until datetime,
at_date datetime,
constraint ch_sn check(since is null and until is null or
since is not null and until is not null)
)