[英]How to CONSTRAINT such a condition? SQL Server
I need to create a table TEAMS
and create a constraint that the coach ( TeamCoachName
) can just be a coach for just 1 team ( TeamName
). 我需要创建一个表
TEAMS
并创建一个约束,即教练( TeamCoachName
)只能是一个团队( TeamName
)的教练。
/* Table number 2: Teams */
CREATE TABLE TEAMS
(
TeamName VARCHAR(255) UNIQUE,
YearOfFounding INT,
TeamOwnerName VARCHAR(255),
StadiumName VARCHAR(255),
GeographicArea VARCHAR(255)
CHECK (GeographicArea IN ('North','Central','South')),
TeamCoachName VARCHAR(255),
CONSTRAINT Names UNIQUE (TeamName, TeamCoachName),
CONSTRAINT OneTeamCoach
)
这是您的“ Team
表,如果一个教练只能与1个团队行关联,则它只是TeamCoachName
上的UNIQUE CONSTRAINT
。
You can do this with a UDF that takes a TeamName
and a CoachName
and returns "true" if the CoachName
is associated with any other team. 您可以使用带有
TeamName
和CoachName
的UDF来执行此操作,如果CoachName
与任何其他团队相关联,则返回“ true”。
Then check the value of that function in the CHECK constraint. 然后在CHECK约束中检查该函数的值。
(Although actually Jamie raises a good point. If TeamName
is also UNIQUE, then all you need is a UNIQUE constraint on CoachName
. The only way you would need my approach is if the same TeamName
could appear in multiple rows.) (尽管实际上Jamie提出了一个很好的建议。如果
TeamName
也是UNIQUE,那么您所需要的只是对CoachName
的UNIQUE约束。您需要采用我的方法的唯一方法是,如果同一TeamName
可以出现在多行中。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.