Search code examples
mysqlprepare

this dynamic sql is working fine from sql command prompt but if executed from sql file then always returns 0, why?


delimiter //

drop procedure if exists usp_validateUserLogin;

create procedure usp_validateUserLogin(in t varchar(255), 
in username varchar(255), 
in password varchar(255),out count int)
BEGIN
   set @r=0;
   set @tbl=concat('select count(*) into @r from ',t);
   set @tbl2=concat(@tbl,' where @tbl.username=username and @tbl.password=password');
   prepare pstmt from @tbl2;
   execute pstmt;
   set count=@r;
END//

delimiter ;

above code is written in a file and i am executing it from sql command prompt and compiles with no error. when i call this stored procedure it returns every time a zero, although there is only one record which matches input parameter. if i execute same statements from sql command prompt itself then its working correctly.


Solution

  •    set @tbl=concat('select count(*) into @r from ',t, ' t ');
       set @tbl2=concat(@tbl,' where t.username=', username, ' and t.password=', password');
    

    and this question could had been avoided if you had printed the sql statement before try to execute it...