Search code examples
mysqlsqlselectsql-scripts

MySql conditional stop script execution


I need to write SQL script which stops if some values not found in DB. Something like this (pseudo-code):

BEGIN;
...
set @a = (select ... );
if @a IS NULL THEN STOP_WITH_ERROR_AND_ROLLBACK();
...
COMMIT;

Can anybody help to me?

UPDATE: for some reasons, I can't use stored procedures or functions.

UPDATE 2: Note: I don't need explicit rollback. Break of script execution are sufficiently. It automatically rollback changes of not-committed transaction.


Solution

  •     start transaction;
    
        set @a=(select ...);
         -- whatever you want to execute your code like insert, update
    
        set @b=(select if(@a is null,'ROLLBACK','COMMIT'));
        -- @b is store **ROLLBACK** if @a is null nither store **COMMIT**
    
        prepare statement1 from @b;
        -- now statement1 store as @a value
        execute statement1;
    

    i hope it solve your problem.