MySQL - CONCAT - Is there any way to concat a string and use it as a variable?

倾然丶 夕夏残阳落幕 提交于 2019-12-02 07:03:19

If you have variable column name, you will need to use Dynamic SQL:

set @strokes_hole_10 = 6;
set @x = 10;
set @strokes = concat('@strokes_hole_',@x); -- add @ to variable string

-- generate the query string
set @query_str = CONCAT('SELECT ', @strokes);

-- prepare statement using the query string
Prepare stmt From @query_str;

-- executes the prepared statement
Execute stmt;

-- clean up after execution
Deallocate Prepare stmt;

Result

| @strokes_hole_10 |
| ---------------- |
| 6                |

View on DB Fiddle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!