-1
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 AND CodCV AND CodAb 的记录。下面你可以看到我的记录

insert into tImprumuturi(CodCV,CodCD,CodAb)
values('CV21','CD20','ab9')
insert into tImprumuturi(CodCV,CodCD,CodAb)
values('CV21','CD19','ab9')
4

2 回答 2

0
alter table  tImprumuturi add unique index(CodCD, CodCV, CodAb);
于 2013-08-31T21:40:18.263 回答
0

An alternative way to add a unique constraint is to explicitly create a unique index:

create unique index tImprumuturi_CodCD_CodCV_CodAb on tImprumuturi(CodCD, CodCV, CodAb);

You can also do it in the create table statement directly:

create table . . .
    constraint unique(CodCD, CodCV, CodAb)
    . . .

These are both equivalent to the alter table statement in functionality. I happen to prefer the explicit index creation.

EDIT:

Your question still is not clear about what you want to be unique. If you want the individual values not to be repeated, then create a separate unique index on each one:

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);
于 2013-08-31T21:44:47.853 回答