Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to throw SQLException in stored procedure

How can I throw exception in a stored procedure For example:

@temp int =0

As 
BEGIN
SELECT @int = COUNT(*) FROM TABLE1
END

IF(@temp>0)
throw SQL Exception

P/S: not use return value

like image 220
Xitrum Avatar asked Aug 11 '11 12:08

Xitrum


2 Answers

RAISERROR for MSSQL Server. As @Marc Gravell: note the severity must be >= 16 for it to surface as a SqlException.

Read this SO answer for MySQL.

This blog post also shows how to do it in MySQL (if <=6.0)

like image 142
Sunny Milenov Avatar answered Sep 23 '22 03:09

Sunny Milenov


In MySQL there is no way to throw an exception in a stored procedure, but you can force an error by selecting from a non-existing table.
It helps if the tablename gives a description of the error.

Example:

DELIMITER $$

CREATE PROCEDURE throw_exception (IN param1 INTEGER)
BEGIN
  DECLARE testvar INTEGER;
  SELECT testfield INTO testvar FROM atable WHERE id = param1 LIMIT 1;
  IF testfield IS NULL THEN
     /*throw the error here*/
     SELECT * FROM 
       error_testfield_in_atable_not_found_youve_entred_a_nonexisting_id_in_throw_exception;
  END IF;
END $$

DELIMITER ;
like image 44
Johan Avatar answered Sep 20 '22 03:09

Johan