1

In the next portion of code i used a cursor and a loop to generate a list of users who match the search query, but i get a null value, why ?

BEGIN
    DECLARE finished INTEGER DEFAULT 0;
    DECLARE ids TEXT;
    DECLARE response TEXT;
    DECLARE ids_cursor CURSOR FOR
        SELECT id 
        FROM user WHERE email LIKE CONCAT('%',value,'%') 
        OR lastname LIKE CONCAT('%',value,'%') 
        OR name LIKE CONCAT('%',value,'%');
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 2;

    OPEN ids_cursor;
    get_ids: LOOP

        FETCH ids_cursor INTO ids;

        IF finished = 2 THEN
            LEAVE get_ids;
        END IF;

        SET response = CONCAT(ids,";",response);

    END LOOP get_ids;
    CLOSE ids_cursor;

    RETURN response;
END
5
  • Are you getting wrong result or Error Commented Jan 10, 2015 at 9:00
  • Yes , i am getting a null result! Commented Jan 10, 2015 at 9:10
  • i call the function with select name_of_function('test') as response; Commented Jan 10, 2015 at 9:11
  • are you sure the query is succeeding? try set response to 'not foudn' or similar in the IF finished=2 block to debug that. Commented Jan 10, 2015 at 11:30
  • also, you can do this with GROUP_CONCAT: dev.mysql.com/doc/refman/5.6/en/group-by-functions.html Commented Jan 10, 2015 at 11:31

1 Answer 1

1

You do not need to use user defined function you can direcltly fetch the IDs using GROUP_CONCAT() function by below query.

SELECT GROUP_CONCAT(id SEPARATOR ';') AS response
FROM user 
WHERE email LIKE CONCAT('%',value,'%') 
   OR lastname LIKE CONCAT('%',value,'%') 
   OR name LIKE CONCAT('%',value,'%');
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.