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

十年热恋 提交于 2019-12-20 04:47:03

问题


Low hours on mysql but starting to probe the edges. Stackoverflow a great resource - thanks everyone.

Experimenting with Concat I fell over this issue. I know there will be a way but I just can't figure it out.

My example:

set @strokes_hole_10 = 6;
set @x = 10;
set @strokes = concat('strokes_hole_',@x);
select @strokes;

I looking for @strokes to be the variable value 6 rather than the variable value "strokes_hole_10".

I find lots of information on using concat, mostly straight forward examples and I know concat is resulting in a string. I just can't figure out how to make a dynamic label work.

Am I looking at prepared statements as the way to proceed?

Thanks in advance for any help.


回答1:


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



来源:https://stackoverflow.com/questions/53147889/mysql-concat-is-there-any-way-to-concat-a-string-and-use-it-as-a-variable

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