11

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

Xitrum
  • 7,765
  • 26
  • 90
  • 126

2 Answers2

18

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)

Pang
  • 9,564
  • 146
  • 81
  • 122
Sunny Milenov
  • 21,990
  • 6
  • 80
  • 106
1

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 ;
Johan
  • 74,508
  • 24
  • 191
  • 319