MySQL - CONCAT - 有什么方法可以连接字符串并将其用作变量吗?
MySQL - CONCAT - Is there any way to concat a string and use it as a variable?
mysql 时间不多,但开始探索边缘。 Whosebug 一个很好的资源 - 谢谢大家。
使用 Concat 进行试验时,我遇到了这个问题。我知道会有办法,但我就是想不通。
我的例子:
set @strokes_hole_10 = 6;
set @x = 10;
set @strokes = concat('strokes_hole_',@x);
select @strokes;
我希望@strokes 是变量值 6 而不是变量值 "strokes_hole_10"。
我找到了很多关于使用 concat 的信息,主要是直接示例,我知道 concat 会产生一个字符串。我只是不知道如何使动态标签起作用。
我是否将准备好的语句视为继续进行的方式?
在此先感谢您的帮助。
如果您有可变列名,则需要使用 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 |
mysql 时间不多,但开始探索边缘。 Whosebug 一个很好的资源 - 谢谢大家。
使用 Concat 进行试验时,我遇到了这个问题。我知道会有办法,但我就是想不通。
我的例子:
set @strokes_hole_10 = 6;
set @x = 10;
set @strokes = concat('strokes_hole_',@x);
select @strokes;
我希望@strokes 是变量值 6 而不是变量值 "strokes_hole_10"。
我找到了很多关于使用 concat 的信息,主要是直接示例,我知道 concat 会产生一个字符串。我只是不知道如何使动态标签起作用。
我是否将准备好的语句视为继续进行的方式?
在此先感谢您的帮助。
如果您有可变列名,则需要使用 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 |