问题描述
我得到了带有 teams
的表 team_id primary key
和带有外键 pilots
的表 team_id
。我想应用一个约束,不允许我添加超过 2 个具有相同 team_id
解决方法
您可以创建一个函数来计算特定 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