DEV Community

Michael
Michael

Posted on

SELECT INTO with Dynamic SQL in GBase 8a: Use Session Variables, Not Local Ones

A dynamic SQL statement can save its results into a variable with select into — but in the China-domestically developed GBase 8a MPP database from GBASE, that variable cannot be a local variable. It has to be a session-level one. This post shows both attempts in a stored procedure, run from the gbase client.

The local-variable failure

drop procedure if exists get_gc_task2;
delimiter //
create procedure get_gc_task2(in strlen int,in top int)
begin
  declare num int;
  set @executeSQL_sql='select count(*) into num from t1';
  select @executeSQL_sql;
  PREPARE executeSQL_s1 FROM @executeSQL_sql ;
  EXECUTE executeSQL_s1;
  DEALLOCATE PREPARE executeSQL_s1;

  select strlen,top,now(),num from dual;

end//
delimiter ;
call get_gc_task2(1,2);
Enter fullscreen mode Exit fullscreen mode

The call fails:

ERROR 1327 (42000): Undeclared variable: num
Enter fullscreen mode Exit fullscreen mode

The session-variable fix

Session variables start with @ and are visible for the whole current session, so take care not to clash with names used elsewhere — a collision silently produces wrong results. Naming the variable after the procedure, such as @get_gc_task2_AAA, is the safer convention:

drop procedure if exists get_gc_task2;
delimiter //
create procedure get_gc_task2(in strlen int,in top int)
begin
  declare num int;
  set @executeSQL_sql='select count(*) into @get_gc_task2_AAA from t1';
  select @executeSQL_sql;
  PREPARE executeSQL_s1 FROM @executeSQL_sql ;
  EXECUTE executeSQL_s1;
  DEALLOCATE PREPARE executeSQL_s1;
  set num=@get_gc_task2_AAA;
  select strlen,top,now(),num from dual;

end//
delimiter ;
call get_gc_task2(1,2);
Enter fullscreen mode Exit fullscreen mode

The session variable receives the count(*) result, and the local num is then populated from it with set num=@get_gc_task2_AAA;. The original post includes screenshots of the execution results; the author notes the variable was called @AAA there and left it unchanged, so only the extractable text is kept here.

Going forward, the reason is worth remembering: once a statement is prepared and executed dynamically, its context has changed and the caller's local variables are no longer in scope, while session-level ones still are. That is a general property of prepared statements in a gbase cluster, not a quirk of this procedure — so any dynamic SQL in the database that needs to hand a value back should plan for a session variable from the start.

Top comments (0)