Mysql Variable Not Working

Mysql Variable Not Working

I tried to learn about MySQL Variable and do command like this

SET @target=`name`;
SELECT @target FROM transaction_product LIMIT 10;

But it is error and said Unknown column 'name' in 'field list'
Why it is error, i'm sure there is column name on my field list

here is the screenshot of the table

2 Answers

you need to use different quotes 'name' for assigning string to a variable and `name` for column names:

SET @target='name';

to get column value you can use INTO clause:

SELECT `name`
INTO @target
FROM transaction_product
LIMIT 1;

to get multiple rows in single variables you can use GROUP_CONCAT:

SELECT GROUP_CONCAT(`name`)
INTO @target
FROM transaction_product
LIMIT 10;

to execute query dynamically:

SET @target='`name`';

SET @query1 = CONCAT('
    SELECT ',@target,'
    FROM transaction_product
    LIMIT 10'
    );
PREPARE stmt FROM @query1; EXECUTE stmt; DEALLOCATE PREPARE stmt;
2
SELECT @target:=`name` FROM transaction_product LIMIT 10;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Sarah Jenkins
Author

Sarah Jenkins

Sarah Jenkins is a veteran tech journalist with over 12 years of experience covering artificial intelligence, mobile innovations, and digital ethics. Her insights have appeared in leading technology publications worldwide.