SQL 规则取决于所选值

SQL Rules depend on selected value

我有以下简单的数据库:

Table Types:
- ID int
- TypeName nvarchar

Table Users:
- ID int
- UserName nvarchar
- TypeID int

Table BusyTime
- ID int
- UserID int
- BTime time(0)

但有一个限制 - BusyTime 中的记录应该仅针对 TypeID = 3 的用户。TypeID = 1 和 TypeID = 2 的用户不能在 BusyTime 中有记录(这与业务逻辑相矛盾) MSSQL级别怎么形容呢?还是我应该重新设计数据库?

您可以使用检查约束来禁止无效类型: https://technet.microsoft.com/en-us/library/ms188258%28v=sql.105%29.aspx

设置这样的条件约束是可能的。一种方法是将复合索引添加到 users:

create unique index idx_users(type, id) on users(type, id)

然后将其用于外键约束:

alter table busytime add _type as (3) persisted not null;
alter table busytime add constraint foreign key (_type, userId) on users(type, id);

不幸的是,我认为此列需要 persisted,因此它实际上在记录中占据了 space。

不幸的是,我认为这也行不通:

alter table busytime add constraint foreign key (3, userId) on users(type, id);

我假设每个 table 中的主键都在 ID 上。您需要更改的是,在 Users 中的 IDTypeID 上添加 UNIQUE KEY 约束:

ALTER TABLE Users ADD CONSTRAINT UQ_User_Types_XRef (ID,TypeID)

并创建 BusyTime table 为:

CREATE TABLE BusyTime (
   ID int not null,
   UserID int not null,
   BTime time(0) not null,
   _Type_XRef as 3 persisted,
   constraint PK_BusyTime PRIMARY KEY (ID),
   constraint FK_BusyTime_Users FOREIGN KEY (UserID)
        references Users (ID),
   constraint FK_BusyTime_Users_XRef FOREIGN KEY (UserID,_Type_XRef) 
        references Users (ID,TypeID)
)

我假设 PK_BusyTimeFK_BusyTime_Users 是您现有的限制条件。既然 FK_BusyTime_Users_XRef 存在,是否删除 FK_BusyTime_Users(这是 "real" 外键约束)是个人喜好问题。