【问题标题】:MySQL - CONCAT - Is there any way to concat a string and use it as a variable?MySQL - CONCAT - 有没有办法连接字符串并将其用作变量?
【发布时间】:2019-04-08 10:17:22
【问题描述】:

mysql 上的时间很短,但开始探索边缘。 Stackoverflow 是一个很好的资源 - 谢谢大家。

在使用 Concat 进行实验时,我遇到了这个问题。我知道会有办法,但我就是想不通。

我的例子:

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

我希望 @strokes 成为变量值 6 而不是变量值“strokes_hole_10”。

我找到了很多关于使用 concat 的信息,大部分是直接的例子,我知道 concat 会产生一个字符串。我只是不知道如何使动态标签起作用。

我是否将准备好的语句视为继续进行的方式?

提前感谢您的帮助。

【问题讨论】:

  • 这些答案之一是否解决了您的问题?如果没有,您能否提供更多信息来帮助回答?否则,请考虑将最能解决您的问题的答案标记为已接受。见stackoverflow.com/help/someone-answers

标签: mysql variables concat


【解决方案1】:

如果你有可变的列名,你需要使用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                |

View on DB Fiddle

【讨论】:

  • 设置@strokes = concat('@strokes_hole_',@x,' into @var');
  • @ereceles 我不明白你在问什么?您在 concat 中缺少选择
  • 刚刚将变量添加到第三行,以便能够将此结果传递给存储过程。已发布,以便其他人可以看到解决方案。谢谢
猜你喜欢
  • 2011-03-05
  • 2012-03-16
  • 1970-01-01
  • 2011-10-24
  • 2015-05-05
  • 1970-01-01
  • 1970-01-01
  • 2019-12-21
  • 2011-10-25
相关资源
最近更新 更多