MySQL-CONCAT-有什么方法可以连接字符串并将其用作变量? [英] MySQL - CONCAT - Is there any way to concat a string and use it as a variable?

查看:519
本文介绍了MySQL-CONCAT-有什么方法可以连接字符串并将其用作变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在mysql上工作时间很短,但是开始探究边缘. Stackoverflow是一种很好的资源-谢谢大家.

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

与Concat一起进行实验我对这个问题不满意.我知道会有办法,但我只是想不通.

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

我的示例:

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

我希望@strokes是变量值6,而不是变量值"strokes_hole_10".

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

我发现了许多有关使用concat的信息,大多数都是简单的示例,而且我知道concat会生成字符串.我只是不知道如何使动态标签起作用.

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?

在此先感谢您的帮助.

推荐答案

如果您有可变的列名,则需要使用

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;

结果

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


在DB Fiddle上查看

这篇关于MySQL-CONCAT-有什么方法可以连接字符串并将其用作变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆