SQL规则取决于选定的值



我有以下简单的DB:

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中有记录(这与业务逻辑相矛盾)如何在MS SQL级别上描述它?还是应该重新设计DB?

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

ALTER TABLE Users ADD CONSTRAINT UQ_User_Types_XRef (ID,TypeID)

并将BusyTime表创建为:

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(这是"真正的"外键约束)是一个品味问题。

您可以使用检查约束来禁止无效类型: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,所以它实际上占用了记录中的空间。

不幸的是,我认为这也不起作用:

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

最新更新