BEGIN TRY and BEGIN CATCH - SQL Server to MariaDB Migration

In SQL Server, you can use BEGIN TRY and BEGIN CATCH blocks to handle exceptions.

In MariaDB, you can use the DECLARE EXIT HANDLER FOR SQLEXCEPTION.

Consider a sample table with a unique constraint:

   -- Sample table
   CREATE TABLE colors (name VARCHAR(30) PRIMARY KEY NOT NULL);

SQL Server:

  CREATE PROCEDURE sp1
  AS
    BEGIN TRY
      -- Insert the first row
      INSERT INTO colors VALUES('White');
      -- Insert a duplicate that violates the constraint    
      INSERT INTO colors VALUES('White');    
      PRINT 'Ok'    
    END TRY 
 
    BEGIN CATCH
      PRINT 'Error'
    END CATCH
  GO
  /* Commands completed successfully. */
 
  EXEC sp1
  /* Error */

MariaDB:

  DELIMITER //
 
  CREATE PROCEDURE sp1()
  BEGIN
    DECLARE EXIT HANDLER FOR SQLEXCEPTION
    BEGIN
      SELECT 'Error';
    END;
 
      -- Insert the first row
    INSERT INTO colors VALUES('White');
    -- Insert a duplicate that violates the constraint    
    INSERT INTO colors VALUES('White');    
    SELECT 'Ok';    
  END 
  //
  /* Query OK, 0 rows affected */
 
  DELIMITER ;
 
  CALL sp1;
  /* Error */

Note that we use the EXIT handler to stop the execution of statements following the failed statement within the block.

For more information, see SQL Server to MariaDB Migration.