Click here to Skip to main content
15,881,882 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have the following SQL command:
SQL
select COLUMN_NAME
FROM
  INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE
      REFERENCED_TABLE_NAME  = 'persons_data'
  AND REFERENCED_COLUMN_NAME = 'ID'
  AND TABLE_NAME             = 'employees'

This returns the foreign key in the child table employees that is persons_data_ID. My problem is I want to insert a value in that foreign Key field, to illustrate what i need I will show what I tried.

What I have tried:

SQL
INSERT INTO `mySchema`.`persons_data` (`Name En`, `Address`, `National ID`) 
VALUES 
('Noud', 'Tyjkl', '697851');

INSERT INTO `mySchema`.`employees` 
(select COLUMN_NAME
FROM
  INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE
      REFERENCED_TABLE_NAME  = 'persons_data'
  AND REFERENCED_COLUMN_NAME = 'ID'
  AND TABLE_NAME             = 'employees') 
VALUES ( LAST_INSERT_ID());

I expect the previous code to function like the following one but it did not i want to know what is the mistake i did?
SQL
INSERT INTO `mySchema`.`persons_data` (`Name En`, `Address`, `National ID`) 
VALUES 
('Noud', 'Tyjkl', '697851');

INSERT INTO `mySchema`.`employees` 
(persons_data_ID) 
VALUES ( LAST_INSERT_ID());
Posted
Updated 15-Feb-19 9:31am
v2
Comments
CHill60 15-Feb-19 11:12am    
What did it actually do?
Ahmed AE 15-Feb-19 11:18am    
it inserts a 2 rows in 2 relational table that are connected with a foreign key. I want to automatically get the foreign key name between the 2 tables instead of manually writing it and use to to insert data in it
Patrice T 15-Feb-19 14:43pm    
Use Improve question to update your question.
So that everyone can pay attention to this information.

1 solution

The schema names don't match.

Are you trying to hack a Pharmacy database? Looks like it. That's illegal.
 
Share this answer
 
Comments
Ahmed AE 15-Feb-19 15:31pm    
i am not trying to hack any thing, please read the question carefully

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900