开发者

SQL Server Constraints Across Tables

开发者 https://www.devze.com 2022-12-29 01:58 出处:网络
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 w开发者_如何学编程ay to set up a c

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 w开发者_如何学编程ay 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!


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.


  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)
0

精彩评论

暂无评论...
验证码 换一张
取 消