2

I have a problem in mysql stored procedures where the varchar variable in the where clause doesn't return the results. The query is given below.

declare itcode varchar(30);
declare qty int;
declare finished int;
declare testc cursor for 
    select itemcode from mytable limit 0,10;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
open testc;
read_loop:Loop
    fetch testc into itcode;
    if finished=1 then
        leave read_loop;
    end if;
    select sum(Qty) as total from 
            mytable2 
            where itemcode=itcode;
end loop;
close testc;

In the above statement It returns null even though the item code exists on both tables. however if I write the statement with the manually assigned value on the where close as below it works.

select sum(Qty) as total from mytable2 where itemcode='p2343';

I'm unable to figure out why the varchar variable doesn't work on the where clause. Can someone let me help me to figure out how to resolve this type issue?

NOTE: Both tables columns are varchar(30).

Additional Note: When I change the statement as below, it prints the values in the itcode as well.

select sum(Qty) as total,itcode from mytable2 where itemcode=itcode

So the itcode have the value 'p2343' but the above stored procedure is not working.

10
  • is where itemcode like 'p2343'; works? Commented May 12, 2014 at 8:15
  • yes, when I give as string with single quotes it works. But when i assign the variable it didn't work. Commented May 12, 2014 at 8:16
  • and what about where itemcode like itcode; ? Commented May 12, 2014 at 8:18
  • Tried that as well, Didn't work. Commented May 12, 2014 at 8:19
  • Seems your itcode doesn't has value 'p2343'. Commented May 12, 2014 at 8:20

1 Answer 1

2

Problem here is that the procedure is referencing your global variable qty in favour of the Qty column on your mytable2. Try changing this:

declare qty int;

to this

declare v_qty int;
Sign up to request clarification or add additional context in comments.

2 Comments

thanks alot. I was googling all over the place to resolve this. Just to understand, wont the mysql identify the case differences in the field and variable?
Usually depends on the OS. Unix=yes, Windows & Mac OS=no. Check out this for more info: dev.mysql.com/doc/refman/5.7/en/…

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.