简体   繁体   中英

Error with foreign key SQL Server 2012

I have problem with adding foreign key in 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'. Msg 1750, Level 16, State 0, Line 1 Could not create constraint. See previous errors.

The column PredracunID does not exist in table prijem. 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.

  1. Predracun table is not having any key (Unique or Primary) column
  2. To create foreign key in Prijem table you have to have PredracunID column in create table statement.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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