Firebird execute statement within an exists

Asked

Viewed 505 times

0

I would like to know how to pass the table name as parameter

create or alter procedure TESTE (
    TABLENAME varchar(30),
    STATUS varchar(1))
returns (
    INCREMENT integer)
as
declare variable RESULT varchar(254);
begin
  if (STATUS = 'T') then
    begin
      for select rdb$generator_name from rdb$generators
      where rdb$system_flag is distinct from 1 and  rdb$generator_name = 'GEN_' || upper(:TABLENAME) || '_ID' into RESULT do
      execute statement 'select gen_id(' || upper(trim(RESULT)) || ', 0) from rdb$database' into increment;

/* funciona */
      while (exists(SELECT * FROM EMPRESAS WHERE EMPRESAS_ID = :incremento)) do
        incremento = incremento + 1;

/* nao funciona */
/*
      while (exists(execute statement 'select * from ' || trim(:TABLENAME) || ' where ' || trim(:TABLENAME) || '_ID = ' || :increment)) do
        increment = increment + 1;
 */
      suspend;

    end
end

1 answer

0

I decided as follows:

function TConexoesController.Ultimo_Codigo(Tabela,Status:String):Integer;
var
 Query : TFDQuery;
begin
  Query             := TFDQuery.Create(nil);
  Query.Connection  := pegaConexao;
  try
    try
      with Query do
        begin
         Close;
         UnPrepare;
         Sql.Clear;
         if Status = 'T' then
           Sql.Text := 'execute block returns (ULTIMO integer) ' +
                       'as ' +
                       'declare variable incremento integer; ' +
                       'begin ' +
                       '  incremento = gen_id(gen_'+ Tabela +'_id, 1); ' +
                       '  while (exists(select * from '+ Tabela +' where '+ Tabela +'_ID =  :incremento)) do ' +
                       '    incremento = incremento + 1; ' +
                       '  ultimo = incremento; ' +
                       '  suspend; ' +
                       'end'
         else
           Sql.Text := 'select max('+ Tabela +'_ID) as ULTIMO from '+ Tabela;
         Clipboard.AsText := Sql.Text;
         Prepare;
         Open;
        end;
      if not Query.IsEmpty then
        result := Query.FindField('ULTIMO').AsInteger
      else
        result := 1;
    except
      on e: exception do gera_log(e.message);
    end;
  finally
    Query.Free;
  end;

end;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.