0

I have to add 'Woonplaats' to all the people in the table 'Leden' Here is my code and what i am trying to do, i want to link the ID 'ID' from table 'Leden' to ID 'WoonplaatsID' from table 'Woonplaats'

Here is my SQL code

-- 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

-- Relatie maken
ALTER TABLE Leden
    ADD CONSTRAINT [FK_Leden_Woonplaats] 
    FOREIGN KEY (CompanyID)
    REFERENCES Company (ID)
Jari
  • 31
  • 1
  • 7
  • 1
    As per your FK query, where is 'CompanyID' column in 'Leden' table and is there any table named 'Company' also? please clarify. – Vishal Gupta Feb 09 '17 at 09:34
  • If I understood your question correctly this would be duplicate to: http://stackoverflow.com/questions/8842876/primary-and-foreign-key-at-the-same-time –  Feb 09 '17 at 09:53

2 Answers2

0

Assuming that you are trying to create relationship between both tables:

First, confirm that there is an existing Primary key on Woonplaats (WoonplaatsID). If not, run this:

ALTER TABLE Woonplaats ADD PRIMARY KEY (WoonplaatsID);

Note: Child table must not have any record which is not present in Parent table.

Foreign key relation can be made by this:

ALTER TABLE Leden
ADD CONSTRAINT FK_Leden_Woonplaats 
FOREIGN KEY (ID)
REFERENCES Woonplaats (WoonplaatsID);
Vishal Gupta
  • 124
  • 6
0

There is no company id column in Leden table and also there is no table named Company in your query.If you really want to relate Leden(ID) and Woonplaats (WoonplaatsID) then execute below command .

ALTER TABLE Leden ADD CONSTRAINT FK_Leden_Woonplaats FOREIGN KEY (ID) REFERENCES Woonplaats (WoonplaatsID);
Mahesh.K
  • 901
  • 6
  • 15