我在SQL Server 2012中添加外键有问题
create table Predracun
(
PredracunID int not null identity(1,1),
Iznos nvarchar(255),
Datum date,
Opis nvarchar(255)
)
create table Racun
(
RacunID int not null identity (1,1),
Sifra nvarchar(255),
BrojRacuna nvarchar(255)
)
create table Prijem
(
PrijemID int not null identity (1,1),
Datum date,
Opis nvarchar(255)
)
alter table Prijem
add constraint FK_PrijemPredracun
foreign key (PredracunID)
references Predracun (PredracunID)
以这种方式添加
我收到了错误信息
消息1769,级别16,状态1,行1外键“FK_UredjajPrijem”在引用表'Uredjaj'中引用无效列'PrijemID'。消息1750,级别16,状态0,行1无法创建约束。查看以前的错误。
使用以下脚本:
CREATE TABLE Predracun
(
PredracunID int not null identity(1,1),
Iznos nvarchar(255),
Datum date,
Opis nvarchar(255)
PRIMARY KEY CLUSTERED
(
[PredracunID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
create table Racun
(
RacunID int not null identity (1,1),
Sifra nvarchar(255),
BrojRacuna nvarchar(255)
)
create table Prijem
(
PrijemID int not null identity (1,1),
PredracunID int,
Datum date,
Opis nvarchar(255)
)
alter table Prijem
add constraint FK_PrijemPredracun
foreign key (PredracunID)
references Predracun (PredracunID)
注意:只能在引用表的主键列或唯一键列上创建外键。你在脚本中遗漏了两件事。
表prijem中不存在PredracunID列。因此它不能用作外键。