[英]Error with foreign key SQL Server 2012
I have problem with adding foreign key in SQL Server 2012 我在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)
added on this way 以这种方式添加
and I got error msg 我收到错误消息
Msg 1769, Level 16, State 1, Line 1 Foreign key 'FK_UredjajPrijem' references invalid column 'PrijemID' in referencing table 'Uredjaj'.
消息1769,级别16,状态1,行1外键'FK_UredjajPrijem'引用了引用表'Uredjaj'中的无效列'PrijemID'。 Msg 1750, Level 16, State 0, Line 1 Could not create constraint.
消息1750,级别16,状态0,第1行无法创建约束。 See previous errors.
请参阅先前的错误。
The column PredracunID does not exist in table prijem. 表prijem中不存在PredracunID列。 Therefore it can't be used as a foreign key.
因此,它不能用作外键。
Use below scripts: 使用以下脚本:
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)
Note: Foreign key can be created only on either primary key column or unique key column from reference table. 注意:只能在参考表的主键列或唯一键列上创建外键。 You were missing two things in your script.
您在脚本中丢失了两件事。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.