将表限制为具有相同外键 id 的行不超过 2 行

时间:2021-05-29 09:06:46

标签: sql-server check-constraints

我得到了带有 teams 的表 team_id primary key 和带有外键 pilots 的表 team_id。我想应用一个约束,不允许我添加超过 2 个具有相同 team_id

的飞行员

1 个答案:

答案 0 :(得分:0)

您可以创建一个函数来计算特定 team_id 的飞行员数量,然后检查约束中的函数。

类似于:

CREATE FUNCTION dbo.FnHowManyPilots(@team_id INT)  
RETURNS int  
AS   
BEGIN  
   DECLARE @pilot_count int
   SELECT @pilot_count = COUNT(*)
   FROM pilots
   WHERE team_id = @team_id
   RETURN @pilot_count
END;  

然后添加一个约束:

ALTER TABLE pilots  
ADD CONSTRAINT chkPilotCount CHECK (dbo.FnHowManyPilots(team_id) <= 2 );  
GO  
相关问题