如何使用 execute 语句为变量赋值

How to assign value to a variable using an execute statement

我需要沿着这条线执行代码

select @a := id from B limit @i ,1 

但是 mysql 不允许在 limit 中传递变量,所以我尝试了另外两件事

select @proc := concat('select @a := id from B limit ', @i, ',1');
prepare stmt from @proc; 
execute stmt; 

这会报错,

select @proc := concat(' id from B limit ', @i, ',1');
prepare stmt from @proc; 
select @a := execute stmt;

请注意,我之前没有在任何地方声明过@a,但此刻我迷路了,不知道如何进行。

尝试:

MariaDB [_]> SET @`a` := NULL,
    ->           @`proc` := CONCAT('SELECT @`a` := `B`.`id`
    '>                              FROM `B`
    '>                              LIMIT ', IFNULL(@`i`, 0), ', 1
    '>                             ');
Query OK, 0 rows affected (0.00 sec)

MariaDB [_]> PREPARE `stmt` FROM @`proc`;
Query OK, 0 rows affected (0.00 sec)
Statement prepared

MariaDB [_]> EXECUTE `stmt`;
+------------------+
| @`a` := `B`.`id` |
+------------------+
|               10 |
+------------------+
1 row in set (0.00 sec)

MariaDB [_]> DEALLOCATE PREPARE `stmt`;
Query OK, 0 rows affected (0.00 sec)

MariaDB [_]> SELECT @`a`;
+------+
| @`a` |
+------+
|   10 |
+------+
1 row in set (0.00 sec)

更新

另一个不使用 CONCAT 函数的选项。

MariaDB [_]> SET @`a` := NULL,
    ->           @`i` := IFNULL(@`i`, 0);
Query OK, 0 rows affected (0.00 sec)

MariaDB [_]> PREPARE `stmt` FROM 'SELECT @`a` := `B`.`id`
    '>                            FROM `B`
    '>                            LIMIT ?, 1
    '>                           ';
Query OK, 0 rows affected (0.00 sec)
Statement prepared

MariaDB [_]> EXECUTE `stmt` USING @`i`;
+------------------+
| @`a` := `B`.`id` |
+------------------+
|               10 |
+------------------+
1 row in set (0.00 sec)

MariaDB [_]> DEALLOCATE PREPARE `stmt`;
Query OK, 0 rows affected (0.00 sec)

MariaDB [_]> SELECT @`a`;
+------+
| @`a` |
+------+
|   10 |
+------+
1 row in set (0.00 sec)