2

Hi hope you guys can help.

I am trying to throw an error Message inside a Function if the Input (INT) isn't equal to length 8.

My Code:

DELIMITER $$
CREATE FUNCTION test(a INT)
RETURNS INT
BEGIN
    DECLARE ret INT;
    IF LENGTH(CONVERT(a, CHAR)) != 8 THEN SIGNAL SQLSTATE '4500' SET MESSAGE_TEXT = 'need to be 8!';
    END IF;
    IF a <= 20000000 THEN SET ret = 1;
    ELSEIF a > 20000000 AND a <= 30000000 THEN SET ret = 2;
    ELSE SET ret = 3;
    END IF;
    RETURN ret;
END;
$$
DELIMITER ;

Unfortunately when i create the Function it instantly throws the error message and doesn't wait for the condition. So when i am trying to run the Code it says:

Error Code: 1407. Bad SQLSTATE: '4500'

How can i solve that??

1
  • SQLSTATEs are 5-byte codes, you're trying to set up a 4-byte one. Commented Sep 5, 2023 at 19:10

1 Answer 1

3
DELIMITER $$
CREATE FUNCTION test(a INT)
RETURNS INT
BEGIN
    DECLARE ret INT;
    IF LENGTH(CONVERT(a, CHAR)) != 8 THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'need to be 8!';   #--I had made changes at this line#
    END IF;
    IF a <= 20000000 THEN SET ret = 1;
    ELSEIF a > 20000000 AND a <= 30000000 THEN SET ret = 2;
    ELSE SET ret = 3;
    END IF;
    RETURN ret;
END;
$$
DELIMITER ;

Try above code. There is no SQLSTATE with 4500.Instead of 4500 you can try 45000 SQLSTATE

Hope this will help you.

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

4 Comments

@Sagnar Gangwal First of all thanks a lot for your answer. I was able to create the function. Unfortunately the condition doest work. If the input isn't equal to 8 the Function doesn't calculate ret wich is fine but it also doesn't throw the message 'need to be 8!'. I tried calling the function using: SELECT test(223941245). Do you maybe see the next dumb mistake i do? haha
@user7992920 I had tried same,and got proper error message as shown in below image
I think the ; after the end statement should be deleted. But otherwise it work for me too.
One correction: the SQLSTATE you can apply doesn't need to exist in the documentation, but needs to be well-formed (5-byte, with two alphanumeric characters and three number characters following). 45 is the class specifically for user-defined SQLSTATEs, but the following number can be anything, not necessarily 000. You can also use other classes, if you feel it's appropriate for your application; however keep in mind that they might someday get reserved for some other system use.

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.