寻找有关必须实现唯一性的 table 约束条件的建议
Looking for suggestions on what table constraints to have to achieve uniqueness
在 sql-服务器 table 中期望如下数据:
具有 id1 的资源将针对不同的版本条目,并且还可以针对不同的版本具有不同的名称。
但是Name不能在资源之间共享。一旦 id1 使用 NameX,其他资源将不能使用相同的名称。
请建议 sql-table 我可以定义的约束条件:
ID 名称 版本
------------------
id1 名称 1 1
id1 名称 1 2
id1 名称A 3
id1 名称 X 4
id2 名称 2 1
id2 NameX 2 --无效记录,NameX已经被id1使用
创建一个触发器,在插入新记录之前检查值是否存在,如果记录存在则抛出错误
像这样
CREATE TRIGGER ti_CheckRecord
on YourTable before insert
begin
if exists(select 1 from inserted where exists(select 1 from yourtable where name = inserted.name and id <> inserted.id))
begin
--write your error code here
end
end
您可以使用具有多个唯一索引的索引视图来确保每个名称在视图中的每个 id 值只出现一次,然后使完整的名称集唯一:
create table dbo.Ix (ID varchar(20) not null, Name varchar(20) not null,
Version int not null)
go
create view dbo.DRI_Ix_Unique_Names
with schemabinding
as
select
Id,Name,COUNT_BIG(*) as Cnt
from
dbo.Ix
group by
ID,Name
go
create unique clustered index IX_DRI_IX_Unique_Names on dbo.DRI_Ix_Unique_Names (Id,Name)
go
create unique nonclustered index IX_DRI_IX_Unique_Names_Only on
dbo.DRI_Ix_Unique_Names(Name)
go
insert into dbo.Ix(ID,Name,Version) values
('id1','Name1',1)
go
insert into dbo.Ix(ID,Name,Version) values
('id1','Name1',2)
go
insert into dbo.Ix(ID,Name,Version) values
('id1','NameA',3)
go
insert into dbo.Ix(ID,Name,Version) values
('id1','NameX',4)
go
insert into dbo.Ix(ID,Name,Version) values
('id2','Name2',1)
go
insert into dbo.Ix(ID,Name,Version) values
('id2','NameX',2)
这导致五次成功的插入,随后出现错误,因为最后一次插入违反了非聚集唯一索引。
我不确定版本列如何影响您的要求,并且我没有在任何约束中使用它。
在 sql-服务器 table 中期望如下数据:
具有 id1 的资源将针对不同的版本条目,并且还可以针对不同的版本具有不同的名称。
但是Name不能在资源之间共享。一旦 id1 使用 NameX,其他资源将不能使用相同的名称。
请建议 sql-table 我可以定义的约束条件:
ID 名称 版本 ------------------ id1 名称 1 1 id1 名称 1 2 id1 名称A 3 id1 名称 X 4 id2 名称 2 1 id2 NameX 2 --无效记录,NameX已经被id1使用
创建一个触发器,在插入新记录之前检查值是否存在,如果记录存在则抛出错误
像这样
CREATE TRIGGER ti_CheckRecord
on YourTable before insert
begin
if exists(select 1 from inserted where exists(select 1 from yourtable where name = inserted.name and id <> inserted.id))
begin
--write your error code here
end
end
您可以使用具有多个唯一索引的索引视图来确保每个名称在视图中的每个 id 值只出现一次,然后使完整的名称集唯一:
create table dbo.Ix (ID varchar(20) not null, Name varchar(20) not null,
Version int not null)
go
create view dbo.DRI_Ix_Unique_Names
with schemabinding
as
select
Id,Name,COUNT_BIG(*) as Cnt
from
dbo.Ix
group by
ID,Name
go
create unique clustered index IX_DRI_IX_Unique_Names on dbo.DRI_Ix_Unique_Names (Id,Name)
go
create unique nonclustered index IX_DRI_IX_Unique_Names_Only on
dbo.DRI_Ix_Unique_Names(Name)
go
insert into dbo.Ix(ID,Name,Version) values
('id1','Name1',1)
go
insert into dbo.Ix(ID,Name,Version) values
('id1','Name1',2)
go
insert into dbo.Ix(ID,Name,Version) values
('id1','NameA',3)
go
insert into dbo.Ix(ID,Name,Version) values
('id1','NameX',4)
go
insert into dbo.Ix(ID,Name,Version) values
('id2','Name2',1)
go
insert into dbo.Ix(ID,Name,Version) values
('id2','NameX',2)
这导致五次成功的插入,随后出现错误,因为最后一次插入违反了非聚集唯一索引。
我不确定版本列如何影响您的要求,并且我没有在任何约束中使用它。