Mid From PDF SQL SQL & Databases

How do you handle error handling in stored procedures?

Error handling is an essential part of stored procedures. Here’s how you handle errors in

different databases:

SQL Server: Use TRY...CATCH blocks to handle errors.

BEGIN TRY

  • - Some SQL operation

INSERT INTO employees (name) VALUES ('John Doe');

END TRY

BEGIN CATCH

SELECT ERROR_MESSAGE() AS ErrorMessage;

END CATCH;

  • PostgreSQL: Use EXCEPTION blocks in PL/pgSQL.

BEGIN

  • - Some SQL operation

INSERT INTO employees (name) VALUES ('John Doe');

EXCEPTION

WHEN others THEN

RAISE NOTICE 'Error occurred: %', SQLERRM;

END;

  • MySQL: MySQL doesn't have a built-in TRY...CATCH, but you can use

DECLARE...HANDLER.

DELIMITER //

CREATE PROCEDURE ExampleProcedure()

BEGIN

DECLARE CONTINUE HANDLER FOR SQLEXCEPTION

SELECT 'An error occurred';

  • - Some SQL operation

INSERT INTO employees (name) VALUES ('John Doe');

END //

DELIMITER ;

More from SQL Server Tutorial

All questions for this course
Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details