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

时间:2016-06-10 07:32:24

标签: dynamic mariadb

我需要沿着这一行执行代码

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

然而,mysql不允许在限制中传递变量,所以我尝试了另外两件事

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,但此时我迷路了,不知道如何继续。

1 个答案:

答案 0 :(得分:1)

尝试:

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)