lundi 13 février 2017

Can't make relation SQL tables

Vote count: 0

i am trying to make a relation with the table 'Leden' and 'Woonplaats' but i am getting this error message:

Msg 547, Level 16, State 0, Line 2
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_Leden_Woonplaats". The conflict occurred in database "Familie", table "dbo.Woonplaats", column 'WoonplaatsID'.

I have to make a relation like when I select a ID on 'Familie' it needs to show the correct 'Woonplaats' of the ID.

Here is the SQL code i run:

-- Master gebruiken en Database Familie aanmaken
USE master
CREATE Database Familie
go
-- DROP Database Familie

-- Familie databse gebruiken
USE Familie

-- Tabel Leden maken
CREATE TABLE Leden
(
ID int NOT NULL,
Voornaam varchar(225),
Achternaam varchar(255),
Leeftijd int,
Moeder int,
Vader int
)
-- DROP table Leden

-- Tabel Woonplaats maken
CREATE TABLE Woonplaats
(
WoonplaatsID int NOT NULL,
Woonplaats varchar(225),
)
-- DROP Table Woonplaats

-- Gegevens in tabel Leden toevoegen
INSERT INTO Leden (ID, Voornaam, Achternaam, Leeftijd, Moeder, Vader)
VALUES (1, 'Sandra','Rengeling', 49, 3, 4),
(2, 'Erik','Rengeling', 50, 9, 10),
(3, 'Claar','Aarts', 78, 0, 0),
(4, 'Piet','Aarts', 80, 0, 0),
(5, 'Petra','van de Werken', 45, 3, 4),
(6, 'Patrick','van de Werken', 47, 11, 12),
(7, 'Jari','Rengeling', 19, 1, 2),
(8, 'Romy','Rengeling', 17, 1, 2),
(9, 'Inge','Rengeling', 82, 0, 0),
(10, 'Henk','Rengeling', 85, 0, 0),
(11, 'Jan','van de Werken', 78, 0, 0),
(12, 'Monique','van de Werken', 75, 0, 0)
-- TRUNCATE TABLE Leden

-- Gegevens in tabel Woonplaats toevoegen
INSERT INTO Woonplaats (WoonplaatsID, Woonplaats)
VALUES (101, 'Ammerzoden'),
(102, 'Zaltbommel'),
(103, 'Hedel')
-- TRUNCATE Table Woonplaats

-- Primary key tabel Leden
ALTER TABLE Leden ADD PRIMARY KEY (ID);

-- Primary key tabel Woonplaats
ALTER TABLE Woonplaats ADD PRIMARY KEY (WoonplaatsID);

-- Relatie maken
ALTER TABLE Leden
ADD CONSTRAINT FK_Leden_Woonplaats 
FOREIGN KEY (ID)
REFERENCES Woonplaats (WoonplaatsID);


SELECT * FROM Leden

SELECT * FROM Woonplaats

asked 9 secs ago

Let's block ads! (Why?)



Can't make relation SQL tables

Aucun commentaire:

Enregistrer un commentaire