在 MySQL 中的字符串中多次连接一个变量

Concatenating a variable multiple times in string in MySQL

场景: 我正在尝试将一个字符串设置为一个变量,然后将其传递给准备好的语句。我正在使用 "concat" 函数来创建将要传递的字符串。

查询:

set @floatvar := 'test1'    
set @random_var2 := concat('SELECT ', @floatvar, ' AS Fields, COUNT(CASE WHEN ', @floatvar, ' IS NULL THEN 1 END) AS NullCount');

Obs: 我的查询有更多的部分要包含在字符串中,但即使只有这个我也遇到了麻烦,所以我一步一步地做。

问题: 当我尝试 运行 时,第 2 行出现语法错误(SQL 错误 1064)。我不知道为什么会这样。

问题:是什么导致了这个问题,如何解决?

没有像这样的SELECT .. INTO ..:

SELECT 
 concat('SELECT ', @floatvar, ' AS Fields, COUNT(CASE WHEN ', @floatvar, ' IS NULL THEN 1 END) AS NullCount')
INTO @myquery;

样本

MariaDB [test]> SET @floatvar := 'test1'    ;
Query OK, 0 rows affected (0.002 sec)

MariaDB [test]> SELECT
    ->  concat('SELECT ', @floatvar, ' AS Fields, COUNT(CASE WHEN ', @floatvar, ' IS NULL THEN 1 END) AS NullCount')
    -> INTO @myquery;
Query OK, 1 row affected (0.000 sec)

MariaDB [test]>
MariaDB [test]> SELECT @myquery;
+--------------------------------------------------------------------------------+
| @myquery                                                                       |
+--------------------------------------------------------------------------------+
| SELECT test1 AS Fields, COUNT(CASE WHEN test1 IS NULL THEN 1 END) AS NullCount |
+--------------------------------------------------------------------------------+
1 row in set (0.000 sec)

MariaDB [test]>
set @floatvar := 'test1' ;

set @random_var2 := (select concat('SELECT ', @floatvar, ' AS Fields, COUNT(CASE WHEN ', @floatvar, ' IS NULL THEN 1 END) AS NullCount'));

select @random_var2; 

给这个

SELECT test1 AS Fields, COUNT(CASE WHEN test1 IS NULL THEN 1 END) AS NullCount;

结果

ERROR 1054 (42S22): Unknown column 'test1' in 'field list'

如果你这样做

prepare sqlstmt = @random_var2;
execute sqlstmt;
deallocte prepare sq;stmt;

结果

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '= @random_var2' at line 1

最好在触发动态 sql 之前检查准备好的语句是否有效,因为来自动态 sql 的错误消息可能没有帮助。