简体   繁体   English

如何在SQL Server 2008(R2)中的更多列上添加唯一约束?

[英]How to add an unique constraint on more columns in SQL Server 2008 (R2)?

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)
  ) 

I don't want to have many of the same CodCD OR CodCV OR CodAb but never two records with the same CodCD AND CodCV AND CodAb. 我不想有许多相同的CodCD或CodCV或CodAb,但是永远不会有两个记录具有相同的CodCD AND CodCV和CodAb。 My code is at the top as you can see, and even if I have the instruction CONSTRAINT ucCodes UNIQUE (CodCD,CodCV,CodAb) , it still let me to insert two or more records with the same CodCD and CodCV and CodAb . 如您所见,我的代码位于顶部,即使我有CONSTRAINT ucCodes UNIQUE (CodCD,CodCV,CodAb)指令CONSTRAINT ucCodes UNIQUE (CodCD,CodCV,CodAb) ,它仍然允许我插入两个或多个具有相同CodCDCodCVCodAb Below you can see my records 在下面可以看到我的记录

insert into tImprumuturi(CodCV,CodCD,CodAb)
values('CV21','CD20','ab9'),
      ('CV21','CD19','ab9')
CONSTRAINT ucCodes UNIQUE (CodCD, CodCV, CodAb) 

The above sets a unique constraint on those three values, as if they were one value. 上面对这三个值设置了唯一约束,就好像它们是一个值一样。

This would mean that the following would work: 这意味着以下将起作用:

set values('a', 'b', 'c'),
          ('a', 'b', 'd')

and the following would fail: 并且以下操作将失败:

set values('a', 'b', 'c'),
          ('a', 'b', 'c')

EDIT 编辑

In response to your comment, you could do the following: 为了回应您的评论,您可以执行以下操作:

CONSTRAINT ucCodCD UNIQUE (CodCD, CodCV) 
CONSTRAINT ucCodCV UNIQUE (CodCD, CodAb) 
CONSTRAINT ucCodAb UNIQUE (CodCV, CodAb)

This would mean that the following would work: 这意味着以下将起作用:

set values('a', 'b', 'c'),
          ('a', 'd', 'e')

and the following would fail: 并且以下操作将失败:

set values('a', 'b', 'c'),
          ('a', 'b', 'd')

Its working exactly as you have defined it in the table. 它的工作方式与您在表中定义的完全相同。 As you have created constraint on the combination of CodCV,CodCD,CodAb, so here ('CV21','CD20','ab9') and ('CV21','CD19','ab9') would be considered as unique.(value is different for CodCD). 由于您已对CodCV,CodCD,CodAb的组合创建了约束,因此此处('CV21','CD20','ab9')和('CV21','CD19','ab9')将被视为唯一。 (CodCD的值不同)。 May be you should try creating 2 separate unique constraint as following: 也许您应该尝试创建2个单独的唯一约束,如下所示:

CONSTRAINT ucCod_CD UNIQUE (CodCD) 
CONSTRAINT ucCod_CV UNIQUE (CodCV) 
CONSTRAINT ucCod_Ab UNIQUE (CodAb)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM