Search code examples
mysqlvariablesstored-procedures

Stored Procedure outputs empty results but query is successful


I am very new to stored procedures with MYSQL.

If I run this code on my server

select * from groupover o
left join groupatt a on o.myindex = a.myindex and a.sessid = 20231
where o.univ = 'UofU';

I get my list of results successfully.

However when I transfer that select statement into a stored procedure where I am converting the sessid and university into variables it returns an empty result set.

I use the call command with the same information from above. call getgroups("20231","UofU");

This is my Stored Procedure.

CREATE DEFINER=`fsadmin`@`142.184.89.102` PROCEDURE `getgroups`(
    IN mysessid text(5),
    IN myuniv text(10),
)
BEGIN
    declare mywhere longtext;
    IF myuniv != "N/A" THEN
        set mywhere = concat("o.univ = ", myuniv);
        select * from groupover o
        left join groupatt a on o.myindex = a.myindex and a.sessid = mysessid
        where mywhere;
    END IF;
END

I am at a total loss and any help will be appreciated.


Solution

  • The condition:

    where mywhere;
    

    will not work as it makes the query be:

        select * from groupover o
        left join groupatt a on o.myindex = a.myindex and a.sessid = mysessid
        where 'o.univ = myuniv_parameter_value';
    

    i.e, the condition becomes a plain string.

    What you can do:

        select * from groupover o
        left join groupatt a on o.myindex = a.myindex and a.sessid = mysessid
        where o.univ = myuniv;
    

    Alternatively use dynamic SQL (PREPARE, EXECUTE...)