0

I've written a function but it gives me mistake a the second line (create statement) if anyone could help me, I really appreciate:

CREATE FUNCTION GetPrefix (phone_num VARCHAR(30)) RETURNS varchar(30)

deterministic
BEGIN

DECLARE x  INT;
DECLARE prefix varchar(30);
SET x = 0;

for prefix in SELECT code
    FROM tab_len
while (length(phone_num)) > 0
    do
    if prefix<>left(phone_num, length(phone_num)-x)
        then  set x=x+1  ;
    else return 1 ;
END while ;

END $$;

and I receive this error :

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'for prefix in SELECT code FROM tab_len while (length(phone_n' at line 9

1
  • Well, maybe you shouldn't try to come up with your own syntax, but try to find the correct syntax in the manual. And your code makes absolutely no sense. Maybe you should rather describe, what you're trying to do first Commented Apr 21, 2015 at 14:24

1 Answer 1

2
DELIMITER $$
DROP FUNCTION IF EXISTS GetPrefix $$
CREATE FUNCTION GetPrefix 
(
phone_num VARCHAR(30)
) 
RETURNS varchar(30)

BEGIN

DECLARE var_x  INT DEFAULT 0;
DECLARE var_prefix VARCHAR(100);
SET phone_num = IFNULL(phone_num,'');

-- your logic will go here.
return phone_num;


END$$ 
DELIMITER ;

SELECT GetPrefix('test');

This is right syntax to write a function in mysql. check out the differences. Take a look Here

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

Comments

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.