create table tImprumuturi
(
ID_Imprumut int identity primary key,
DataImprumut date default getdate(),
DataScadenta as (dateadd(day,2,DataImprumut)) persisted,
CodCD char(10) foreign key references tCD(CodCd)not null,
CodCV char(10) foreign key references tCaseteVideo(CodCaseta),
CodAb char(10) foreign key references tAbonati(CodAbonat) not null,
CONSTRAINT ucCodes UNIQUE (CodCD,CodCV,CodAb)
)
我不想拥有许多相同的CodCD或CodCV或CodAb,但从来没有两个具有相同CodCD和CodCV和CodAb的记录。我可以看到我的代码在顶部,即使我有指令CONSTRAINT ucCodes UNIQUE (CodCD,CodCV,CodAb)
,它仍然允许我插入两个或多个具有相同CodCD和CodCV和CodAb的记录。您可以在下面看到我的记录
insert into tImprumuturi(CodCV,CodCD,CodAb)
values('CV21','CD20','ab9')
insert into tImprumuturi(CodCV,CodCD,CodAb)
values('CV21','CD19','ab9')
答案 0 :(得分:0)
alter table tImprumuturi add unique index(CodCD, CodCV, CodAb);
答案 1 :(得分:0)
添加唯一约束的另一种方法是显式创建唯一索引:
create unique index tImprumuturi_CodCD_CodCV_CodAb on tImprumuturi(CodCD, CodCV, CodAb);
您也可以直接在create table
语句中执行此操作:
create table . . .
constraint unique(CodCD, CodCV, CodAb)
. . .
这些都与功能中的alter table
语句等效。我碰巧更喜欢显式索引创建。
编辑:
您的问题仍然不清楚您想要独特的内容。如果您希望不重复单个值,则在每个值上创建一个单独的唯一索引:
create unique index tImprumuturi_CodCD_CodCV_CodAb on tImprumuturi(CodCD);
create unique index tImprumuturi_CodCD_CodCV_CodAb on tImprumuturi(CodCV);
create unique index tImprumuturi_CodCD_CodCV_CodAb on tImprumuturi(CodAb);