Click here to Skip to main content
15,882,152 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to insert into a MySQL table (child table) column a certain value(int value). I know that the column name is:
'parent_data_ID'
But that column name is got from the following command:
SQL
SELECT COLUMN_NAME
FROM
  information_schema.KEY_COLUMN_USAGE
WHERE
  REFERENCED_TABLE_NAME = 'parent'
  and 
  TABLE_NAME = 'child'
  AND REFERENCED_COLUMN_NAME = 'ID';


What I have tried:

I have tried the following command:
insert into `pharmacy_schema`.`employees`
(SELECT COLUMN_NAME
FROM
  information_schema.KEY_COLUMN_USAGE
WHERE
  REFERENCED_TABLE_NAME = 'persons_data'
  and 
  TABLE_NAME = 'employees'
  AND REFERENCED_COLUMN_NAME = 'ID')
  values('5');

But an error occurred because the column name is a string not a column name, So what should i do to retrieve the column name and use it in insertion operations?
Posted
Updated 21-Feb-19 5:11am
Comments
Richard Deeming 22-Feb-19 11:22am    
REPOST
This is the same question you posted last week:
https://www.codeproject.com/Questions/1277429/How-do-I-insert-a-value-using-select-statement-in[^]

If you want to update your question to add more information, go to the original question and click the green "Improve question" link. DO NOT post your update as a new question.

1 solution

AFAIK, you cannot directly parameterize a column name like this:
INSERT INTO table (@columnName = @value)

in SQL.

You could, however, build your SQL statement in your application code and just place the name in the SQL query string. However, you better be damn sure it's not possible for just anyone to trick your code into building an SQL statement that could destroy your database. This isn't exactly a secure way to do things by an stretch of the imagination.

You'd be better off using a CASE in the INSERT statement somehow to use the columnname parameter to select the correct column name, though I can't really say that it's even legal to do so. I don't have the time right now to look it up or test it.
 
Share this answer
 
v2

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