如何强制执行包含多个表的唯一性规则?

发布于 2024-11-08 02:10:22 字数 189 浏览 1 评论 0原文

例如,拥有以下表:

Companies (CompanyID)
Workers (WorkerID, CompanyID)
Users (WorkerID, Username)

定义了正确的关系后,如何强制执行以下断言:用户的用户名在其员工所在的公司中是唯一的

For example, having the tables:

Companies (CompanyID)
Workers (WorkerID, CompanyID)
Users (WorkerID, Username)

With the correct relationships defined, how do I enforce the predication that a User's Username is unique in the company where its worker is in?

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

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

发布评论

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

评论(3

送君千里 2024-11-15 02:10:22

为此,您可以使用索引视图。

CREATE VIEW dbo.EnforceConstraint
WITH SCHEMABINDING
AS
SELECT CompanyID, Username
FROM dbo.Users u 
    JOIN dbo.Workers w ON w.WorkerID = u.WorkerID

GO

CREATE UNIQUE CLUSTERED INDEX ix ON dbo.EnforceConstraint(CompanyID, Username)

需要打开某些 SET 选项才能修改索引视图的基表,但如果您使用的是 SQL Server 2005+,则默认情况下这些选项是打开的。

You can use an indexed view for this

CREATE VIEW dbo.EnforceConstraint
WITH SCHEMABINDING
AS
SELECT CompanyID, Username
FROM dbo.Users u 
    JOIN dbo.Workers w ON w.WorkerID = u.WorkerID

GO

CREATE UNIQUE CLUSTERED INDEX ix ON dbo.EnforceConstraint(CompanyID, Username)

There are certain SET options that need to be on for modification of the base tables of indexed views but if you are on SQL Server 2005+ these are on by default.

还不是爱你 2024-11-15 02:10:22

您不能直接这样做,但您确实有几个选项:

  1. 稍微对 Users 表进行非规范化并向其中添加 CompanyID。

  2. 使用插入/更新触发器进行验证。

You can't directly, but you do have a couple options:

  1. Denormalize the Users table a bit and add the CompanyID to it.

  2. Use an insert/update trigger to do the validation.

痕至 2024-11-15 02:10:22

您还可以考虑:

在此处输入图像描述

并确保 WorkerNo 在公司:

alter table Workers
add constraint un_co_wrk unique (CompanyID, WorkerNo) ;

You may also consider:

enter image description here

and to make sure that WorkerNo is unique within the company:

alter table Workers
add constraint un_co_wrk unique (CompanyID, WorkerNo) ;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文