0

I am trying to use following mysql code to insert on column whose name is decided on some value. It gives me error that "some_percent" unknown column 'some_percent' in 'field list'

set @SplitState = `some_percent`;
SET @ID = uuid();
INSERT INTO `rspca_donations`(`id`, `@SplitState`) values (@ID, '100');

Can someone please suggest correct way?

2
  • Is there a column defined in the rspca_donations table called some_percent Commented Mar 19, 2019 at 9:05
  • 2
    You cannot use variables to refer to column or table names. The closest thing you can do is construct the whole query in a variable, then use PREPARE stmt FROM @query (followed by EXECUTE stmt and DROP PREPARE stmt). Commented Mar 19, 2019 at 9:11

1 Answer 1

1

You can't use a user variable to represent a column name in this way. One option here would be to use a prepared statement in MySQL:

SET @SplitState = 'some_percent';
SET @ID = UUID();
SET @sql = CONCAT('INSERT INTO rspca_donations (id, ', @SplitState, ') VALUES (?, 100)');
PREPARE stmt FROM @sql;
EXECUTE stmt USING @ID;
Sign up to request clarification or add additional context in comments.

2 Comments

Tim Biegeleisen, Thanks. It works for two columns. But I have long list of fields to be inserted in my real code.
That sounds like a good topic for another question, my answer is intended to answer what you actually asked above.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.