外键错误 SQL Server 2012

Error with foreign key 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)

以这种方式添加

我收到错误消息

Msg 1769, Level 16, State 1, Line 1 Foreign key 'FK_UredjajPrijem' references invalid column 'PrijemID' in referencing table 'Uredjaj'. Msg 1750, Level 16, State 0, Line 1 Could not create constraint. See previous errors.

tableprijem 中不存在 PredracunID 列。因此它不能用作外键。

使用以下脚本:

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)

注意:只能在引用 table 的主键列或唯一键列上创建外键。您的脚本中遗漏了两件事。

  1. Predracun table 没有任何键(唯一或主)列
  2. 要在 Prijem table 中创建外键,您必须在 create table 语句中包含 PredracunID 列。