SQL Server 跨表约束

发布于 2024-08-31 14:48:53 字数 460 浏览 1 评论 0原文

我有一个 SQL Server 数据库,其中包含一个 Apartment 表(其中包含 FloorNum 列和 BuildingID 列)和一个 ApartmentBuilding 表(带有NumFloors列)。有没有办法设置约束(使用 SQL Server UI)来检查 Apartment.FloorNum 是否大于 ApartmentBuilding.NumFloors

我尝试了这个:

FloorNum > ApartmentBuilding.NumFloors

但现在我意识到我必须以某种方式加入 BuildingID 上的列,但我不知道如何在约束内做到这一点。

感谢您的帮助!

I have a SQL Server database with an Apartment table (which has columns FloorNum and BuildingID) and an ApartmentBuilding table (with column NumFloors). Is there any way to set up a constraint (using the SQL Server UI) to check that Apartment.FloorNum is greater than ApartmentBuilding.NumFloors?

I tried this:

FloorNum > ApartmentBuilding.NumFloors

but now I realize that I somehow have to join the columns on the BuildingID, but I have no idea how to do that within a constraint.

Thanks for your help!

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

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

发布评论

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

评论(2

小耗子 2024-09-07 14:48:53

您不能使用 CHECK CONSTRAINT 来执行此操作,因为它需要来自另一个表的数据。您可以使用 INSERT/UPDATE 触发器

You can't do this with a CHECK CONSTRAINT since it requires data from another table. You would handle this with an INSERT/UPDATE trigger.

两相知 2024-09-07 14:48:53
  1. 在 ApartmentBuilding 表中,在 (BuildingID, NumFloors) 上添加 UNIQUE 约束
  2. 在 Apartment 表中,添加列 NumFloorsInBuilding
  3. 在 Apartment 表中,在 (BuildingID, NumFloorsInBuilding) 上添加引用 (BuildingID, NumFloors) 的外键。这保证了 NumFloorsInBuilding 始终等于父表中的 NumFloors。
  4. 在公寓表中,添加 CHECK(FloorNum < NumFloorsInBuilding)
  1. In ApartmentBuilding table, add UNIQUE constraint on(BuildingID, NumFloors)
  2. In Apartment table, add column NumFloorsInBuilding
  3. In Apartment table, add foreign key on (BuildingID, NumFloorsInBuilding) referring to (BuildingID, NumFloors). This guarantees that NumFloorsInBuilding is always equal to NumFloors in parent table.
  4. In Apartment table, add CHECK(FloorNum < NumFloorsInBuilding)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文