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;
2
  • Has been asked here before: stackoverflow.com/questions/838978/… Commented Mar 6, 2013 at 10:54
  • that question is not about implementation as if statement in a procedure Commented Mar 6, 2013 at 12:58

1 Answer 1

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.)

Sign up to request clarification or add additional context in comments.

3 Comments

how do I implement it in procedure as if statement?
I updated my answer. I hope the syntax is correct. If anyone sees errors, please update the answer.
I suppose it's if name = 'DBName' then but this answers what I needed

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.