指定约束,当其他列不为空时,阻止两列中的任何一列为空?

时间:2013-03-05 09:59:21

标签: tsql constraints

假设我想在表中存储一个区间,其间隔可以指定为单个日期或范围,因此,字段将为:

| id | since | until | at_date |

现在,我希望since is null and until is not nullsince is not null and until is null之类的情况永远不会发生,但since is null and until is nullsince is not null and until is not null都很好(第一个只会很好,如果指定了at_date,那么。

untilsince“合并”到一列可能是有意义的,但在我的情况下,有时候只选择一个或另一个列是有道理的,所以我认为可以他们是分开的。

编辑:

create table menu_availability
(menu_id int not null,
 daily_serving_start time null,
 daily_serving_end time null,
 weekly_service_off tinyint null,
 one_time_service_off date null,
 constraint ch_valid_week_day
    check ((weekly_service_off is null) 
        or (weekly_service_off <= 6 and weekly_service_off >= 0)),
 constraint ch_non_empty_schedule
    check ((daily_serving_start is not null and daily_serving_end is not null)
        or (daily_serving_start is null and daily_serving_end is null)),
 constraint ch_either_week_or_time_set
    check (daily_serving_start is not null 
        or weekly_service_off is not null 
        or one_time_service_off is not null),
 constraint ch_only_week_or_one_time
    check ((weekly_service_off is null and one_time_service_off is not null)
        or (weekly_service_off is not null and one_time_service_off is null)))

这就是我到目前为止......但它真的很乱......

1 个答案:

答案 0 :(得分:2)

我认为您应该删除at_date,并且只对所有间隔使用sinceuntil

使until不具有包容性,因此at_date中的值为“2013-03-01”的值将存储为

since      until
2013-03-01 2013-03-02

<强>更新

您可以使用不允许空值的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)
)