创建 T-SQL 约束以防止表中出现 x 数量的重复记录?

发布于 2024-09-24 00:24:05 字数 336 浏览 1 评论 0原文

table A 中,我有 2 列:

ID (int, PK)
MaxUsers (int)

table B 中,我有 2 列:

ItemID (int)
UserID (int)

table A 中具有匹配 ItemID 的记录数 不能超过 MaxUsers 值。

是否可以编写一个 T-SQL 表约束,使得这种情况在物理上不可能发生?

干杯! 柯特

In table A I have 2 columns:

ID (int, PK)
MaxUsers (int)

In table B I have 2 columns:

ItemID (int)
UserID (int)

The number of records in table A with matching ItemID's cannot exceed the MaxUsers value.

Is it possible to write a T-SQL Table Constraint so that it's not physically possible for this to ever happen?

Cheers!
Curt

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

怕倦 2024-10-01 00:24:05

您可以编写一个插入/更新触发器,在不再满足条件时回滚查询。

You could write an on-insert/update trigger that does a rollback of the query when the conditions are no longer met.

独闯女儿国 2024-10-01 00:24:05

您可以使用“vanilla”约束来做到这一点,例如行级CHECK约束,UNIQUE约束,FOREIGN KEYS,使其具有高度可移植性,例如

CREATE TABLE TableA 
(
 ID INTEGER NOT NULL PRIMARY KEY,
 MaxUsers INTEGER NOT NULL CHECK (MaxUsers > 0), 
 UNIQUE (ID, MaxUsers)
);

CREATE TABLE TableB
(
 ID INTEGER NOT NULL,
 MaxUsers INTEGER NOT NULL, 
 FOREIGN KEY (ID, MaxUsers) 
    REFERENCES TableA (ID, MaxUsers), 
 ID_occurrence INTEGER NOT NULL, 
 CHECK (ID_occurrence BETWEEN 1 AND MaxUsers), 
 UNIQUE (ID, ID_occurrence)
);

为了维护ID_occurrence 序列,您可以创建一个“helper”存储过程或触发器。

You can do this with 'vanilla' constraints e.g. row-level CHECK constraints, UNIQUE constraints, FOREIGN KEYS, making it highly portable e.g.

CREATE TABLE TableA 
(
 ID INTEGER NOT NULL PRIMARY KEY,
 MaxUsers INTEGER NOT NULL CHECK (MaxUsers > 0), 
 UNIQUE (ID, MaxUsers)
);

CREATE TABLE TableB
(
 ID INTEGER NOT NULL,
 MaxUsers INTEGER NOT NULL, 
 FOREIGN KEY (ID, MaxUsers) 
    REFERENCES TableA (ID, MaxUsers), 
 ID_occurrence INTEGER NOT NULL, 
 CHECK (ID_occurrence BETWEEN 1 AND MaxUsers), 
 UNIQUE (ID, ID_occurrence)
);

To maintain the ID_occurrence sequence, you could create a 'helper' stored proc or a trigger.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文