munch
munch

Reputation: 2093

Stored procedure variable not returning expected value in MySQL?

I'm debugging this code

create procedure create_view ( IN t varchar(50)) 
BEGIN
  prepare stmt from 'select @cnt= count( weight ) from test where url = ?;';
  execute stmt using @t;
  set @base = @cnt /4;
  set @offset = @cnt / 2;
  set @query = concat('create or replace view view_by_url as select url, weight from test where url = ',@t,' order by weight limit  ',@base,' , ',@offset,' ;');
  select t as 'param';
  select cnt as 'count';
  select @base as 'base';
  select @offset as 'offset';
  select @query as 'query';
 -- prepare stmt from @query;
 -- execute stmt ;
END;
call create_view('a');

And @t returns 'a' in result set but @cnt, @base and @offset don't. And I can't explain myself why. Can you give me some help?

Upvotes: 1

Views: 337

Answers (2)

munch
munch

Reputation: 2093

The problem seems to be in the SELECT. '=' operator is comparison or something like that while to achieve desired behavior in this case ':=' should be used.

prepare stmt from 'select @cnt= count( weight ) from test where url = ?;';

This change makes the whole piece of code work fine.

Upvotes: 0

sll
sll

Reputation: 62504

Try out single SELECT at the end of stored procedure:

  SELECT 
       t as 'param', 
       @cnt as 'count', 
       @base as 'base', 
       @offset as 'offset', 
       @query as 'query';

Upvotes: 1

Related Questions