0

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

| 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)))

这是我到目前为止所拥有的......但它真的很乱......

4

1 回答 1

2

我认为您应该删除at_date并仅在所有间隔中使用sinceand until

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)
)
于 2013-03-05T10:09:26.820 回答