在异常的情况下设置变量

时间:2016-03-14 07:37:37

标签: mysql stored-procedures

我有一个存储过程,它将设置我的自定义错误,并将out变量设置为某个值。我尝试了以下程序。

***delimiter //
drop procedure if exists test_dalpu //
create procedure test_dalpu(out out_value int)
begin 
DECLARE EXIT HANDLER FOR SQLSTATE '22001'
  BEGIN

set out_value = 1;
SIGNAL SQLSTATE '22001' SET 
  MYSQL_ERRNO = 2,
      MESSAGE_TEXT = 'Too long ';
  END;

insert into abc_test values ( 5,"eerrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr");***


end//
delimiter ;

然后执行

**call test_dalpu(@out_value);**

我得到了正确的输出,因为错误代码2太长了预期,但之后如果我做

select @out_value;

将值设为null而不是1。

这是正确的方法吗?

1 个答案:

答案 0 :(得分:1)

尝试:

mysql> DROP PROCEDURE IF EXISTS `test_dalpu`;
Query OK, 0 rows affected (0.00 sec)

mysql> DROP TABLE IF EXISTS `abc_test`;
Query OK, 0 rows affected (0.00 sec)

mysql> CREATE TABLE IF NOT EXISTS `abc_test` (
    ->     `id` INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    ->     `description` CHAR(10)
    -> );
Query OK, 0 rows affected (0.00 sec)

mysql> DELIMITER //

mysql> CREATE PROCEDURE `test_dalpu`(`out_value` VARCHAR(64))
    -> BEGIN
    ->     DECLARE EXIT HANDLER FOR SQLSTATE '22001'
    ->     BEGIN
    ->         ROLLBACK;
    ->         SET @`set_variable` := CONCAT('SET @`', `out_value`, '` := 1');
    ->         PREPARE `stmt` FROM @`set_variable`;
    ->         EXECUTE `stmt`;
    ->         DEALLOCATE PREPARE `stmt`;
    ->         SIGNAL SQLSTATE '22001' SET
    ->             MYSQL_ERRNO = 2,
    ->             MESSAGE_TEXT = 'Too long';
    ->     END;
    ->     START TRANSACTION;
    ->     INSERT INTO `abc_test`
    ->         (`description`)
    ->     VALUES
    ->         ('ABCDEFGHIJK');
    ->     COMMIT;
    -> END//
Query OK, 0 rows affected (0.00 sec)

mysql> DELIMITER ;

mysql> SET @`out_value` := NULL;
Query OK, 0 rows affected (0.00 sec)

mysql> CALL `test_dalpu`('out_value');
ERROR 2 (22001): Too long

mysql> SHOW WARNINGS;
+-------+------+----------+
| Level | Code | Message  |
+-------+------+----------+
| Error |    2 | Too long |
+-------+------+----------+
1 row in set (0.00 sec)

mysql> SELECT @`out_value`;
+--------------+
| @`out_value` |
+--------------+
|            1 |
+--------------+
1 row in set (0.00 sec)