sql - SQL Server Only Allow True for One of Each Type
问题描述
I have a SQL Server table where I'd like only one of each type to be allowed to be true. For instance, if I had the following structure:
| ID | Sport | IsTheBest |
|:-----|------------|------------:|
| 1 | Basketball | 1 |
| 2 | Basketball | 0 |
| 3 | Basketball | 0 |
| 4 | Basketball | 0 |
| 5 | Baseball | 0 |
| 6 | Baseball | 1 |
| 7 | Baseball | 0 |
I want a constraint in place to ensure that no other record is allowed where Basketball
has IsTheBest
set to true. Said another way, if I tried to edit ID 2 to be IsTheBest
= true
, I want it to fail.
解决方案
You can use a filtered unique index:
create unique index unq_sport_isthebest
on t(sport)
where isthebest = 1;
推荐阅读
- batch-file - 批处理文件分隔限制
- reactjs - @computed 方法在 react + mobx 中不起作用
- java - Android Studio / 如何将 SharedPreferenced 应用于我的代码
- python - 无法执行使用 PyInstaller 构建的 python 脚本
- c# - 列为空或为空的行的 DataTable Rowfilter 语法
- go - 如何正确使用 FirstOrCreate
- google-analytics - 有没有办法查看我的网站上每个月在 Google Analytics 上创建的网页数量?
- angular - Angular 6 一个项目中的多个应用程序 - 如何重定向到子应用程序
- r - 如何将(多页)pdf添加到rmarkdown?
- mapbox - 尝试使用 OSMesa 构建 mapbox 渲染示例应用程序并出现错误