Within a multi-tenant database we have a table that contains some system values and some tenant values defined as follows.
CREATE TABLE [dbo].[ItemTypes] (
[Id] INT IDENTITY PRIMARY KEY
, [TenantId] INT NULL
, [SystemType] BIT NOT NULL
, [Name] VARCHAR(255) NOT NULL
, CONSTRAINT [CK_SYSTEM_TENANT_TYPE] CHECK ((
[TenantId] IS NULL
AND [SystemType] = 1
)
OR (
[TenantId] IS NOT NULL
AND [SystemType] = 0
)
)
);
ALTER TABLE [dbo].[ItemTypes]
ADD CONSTRAINT [UQ_TenantId_Name]
UNIQUE NONCLUSTERED ([TenantId], [Name]);
So an ItemType can either be for all tenants or a single tenant. We have a unique index to ensure that a tenant cannot define two identical ItemTypes.Name.
We also need to ensure that if an ItemType is a SystemType no Tenant can create the same ItemTypes.Name.
Update to Clarify:
For example if we have a System ItemType.Name of 'foo' then no Tenant can create an ItemType.Name of 'foo'.
BUT if there is no System ItemType.Name of 'bar' then every tenant can have its own ItemType.Name of 'bar'
What is the best possible way to do this?