1

I have a procedure in mysql which is doing something with DB, but it needs to throw exception in case that it exist. How do I do that?

I need something like

if exist <db name> then
  SIGNAL SQLSTATE '45002'
  SET MESSAGE_TEXT = 'This database already exist';
end if;
Petr
  • 13,069
  • 17
  • 77
  • 136

1 Answers1

1

You could use this SQL:

SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = 'DBName'

In a procedure it would then be something like this:

DECLARE name TEXT;
SELECT SCHEMA_NAME INTO name FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = 'DBName'
IF name = 'DBName' THEN
   SIGNAL SQLSTATE '45002'
   SET MESSAGE_TEXT = 'This database already exist';
END IF;

(Disclaimer: I haven't written MySQL procedures before and I haven't tested this one. It is only mentioned to give the way of a possible implementation. Also, this example isn't complete.)

Bart Friederichs
  • 32,037
  • 14
  • 96
  • 185