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 options SETthat you must enable to change the underlying tables of indexed views, but if you are on SQL Server 2005+, they are enabled by default.
source
share