简体   繁体   中英

Can I have a MySQL succeed when a subquery fails and fail if the subquery succeeds?

I have a MySQL database and a bunch of stored procedures.

I have a test SQL file which calls the stored procedures to check that they succeed on sample data and populate a test database with example records.

I would also like to have a set of statements which, in pseudocode, would be

SELECT (CALL SomeProc('invalid argument') EMITS ERROR) AS SomeProcCheck;

In this imaginary example, SomeProc is written as

CREATE STORED PROCEDURE SomeProc (arg TEXT)
BEGIN
    IF (IsNotValid(arg))
    THEN
        SIGNAL SQLSTATE '45000';
    END IF;
    INSERT INTO Foo (...);
END

I want my test database init script to verify that failure branches are being hit under the right circumstances.

Can I do this within MySQL?

Use a continue handle and gobble the error, if your call succeeds then signal an error:

DECLARE signalled INT DEFAULT 0;

BEGIN
  DECLARE CONTINUE HANDLER FOR SQLSTATE '45000'
  BEGIN
    SET signalled = 1;
  END;
  CALL SomeProc('invalid argument');
END
IF (signalled = 0)
THEN
    SIGNAL SQLSTATE '45000';
END IF;

Note the scope of the handler so it doesn't handle the second SIGNAL in case the error condition did not happen. I think an exit handler without the signalled flag and subsequent test would also work, but I'm not sure whether the exit is global or just the scope of the handler... this brings me to I don't have a MySql db to test this so sorry for any syntax errors/bugs.

我不记得具体是什么,但使用了一些类似start transaction and set autocommit and rollbackstart transaction and set autocommit and rollback

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM