【发布时间】:2013-06-29 08:32:09
【问题描述】:
这是我的代码示例。我正在使用 sql server 2008 R2
create table Entidade(
NIF numeric(9,0) primary key,
nome varchar(250) not null,
tipoEnt varchar(4) check (tipoEnt in ('CE','EC','CEEC',null))
)
create table Curso(
cod int primary key identity(1,1),
descricao text,
nHoras decimal(5,2),
NIFEnt numeric(9,0) references Entidade(NIF),
)
create table AccaoFormacao(
ref int identity(1,1) not null,
codCr int references Curso(cod) not null,
dtInicio date,
dtFim date,
BIFDR numeric(8,0) references Formador(BI),
constraint pkAccaoFormacao primary key(ref, codCr),
)
create table AF_FDO(
codCr int,
refAf int,
BI numeric(8,0) foreign key references Formando(BI),
constraint fkAF_FDO foreign key(codCr, refAf) references AccaoFormacao(codCr, ref),
constraint pkAF_FDO primary key(codCr, refAf, BI)
)
在我尝试创建表 AF_FDO 之前一切正常,它说: “消息 1776,第 16 级,状态 0,第 1 行 引用表 'AccaoFormacao' 中没有与外键 'fkAF_FDO' 中的引用列列表匹配的主键或候选键。”
我理解该消息,但不知道如何修复它,因为我在约束 pkAccaoFormacao 中声明了主键,这对我来说毫无意义。
AccaoFormacao(codCr, ref) 中的唯一约束有效,但同时它不“适合”我在这里所做的事情。 AccaoFormacao 是 Curso 的弱实体,因此我在 AccaoFormacao 中有一个复合主键。
编辑1: 好吧,我在几个小时后才发现我觉得很愚蠢。 我将 AF_FDO 中的约束 fkAF_FDO 外键(codCr, refAf) 引用 AccaoFormacao(codCr, ref) 更改为约束 fkAF_FDO 外键(codCr, refAf) 引用 AccaoFormacao 并且它起作用了。它将获得AccaoFormacao的复合主键,其他方式也应该工作......
无论如何感谢您的帮助。
【问题讨论】:
-
数字(9,0)主键?这似乎不是一个好的选择......
-
这似乎不是我的问题的原因。我使用数字的原因是因为我想限制该键中的位数,例如信用卡号。
-
没说是。我指出这不是一个好的设计。要么接受,要么离开。
-
好的,谢谢您的建议。
-
添加到@alejandro-rama 的答案,我希望这有助于stackoverflow.com/questions/16085724/…。
标签: sql-server-2008-r2 foreign-keys composite-key