假设我想在表中存储一个区间,其间隔可以指定为单个日期或范围,因此,字段将为:
| 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
都很好(第一个只会很好,如果指定了at_date
,那么。
将until
和since
“合并”到一列可能是有意义的,但在我的情况下,有时候只选择一个或另一个列是有道理的,所以我认为可以他们是分开的。
编辑:
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)))
这就是我到目前为止......但它真的很乱......
答案 0 :(得分:2)
我认为您应该删除at_date
,并且只对所有间隔使用since
和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)
)