SET TERM ^ ;

CREATE OR ALTER function NF_TAM_GRAD (
    MODELO_ID integer,
    TAMANHO integer,
    QTD decimal(15,2),
    DESCI varchar(10))
returns integer
as
declare variable GRADE_CODIGO integer;
declare variable DESC_TAM varchar(300);
begin
  GRADE_CODIGO = coalesce((select first 1 M.grade_codigo FROM tbmodelo M WHERE M.codigo = :MODELO_ID),0);

  DESC_TAM = coalesce((
        select first 1
            G.t01||'|'||G.t02||'|'||G.t03||'|'||G.t04||'|'||G.t05||'|'||G.t06||'|'||G.t07||'|'||G.t08||'|'||G.t09||'|'||G.t10||'|'||
            G.t11||'|'||G.t12||'|'||G.t13||'|'||G.t14||'|'||G.t15||'|'||G.t16||'|'||G.t17||'|'||G.t18||'|'||G.t19||'|'||G.t20
        FROM tbgrade G
        WHERE G.codigo = :GRADE_CODIGO
      ),'|||||||||||||||||||||||||||||||');


  DESC_TAM = fn_array(DESC_TAM, TAMANHO,'|');

  IF(DESC_TAM = DESCI)THEN
  BEGIN
    return QTD;
  END ELSE
  BEGIN
    return 0;
  END

end
^

SET TERM ; ^

SET TERM ^ ;

CREATE OR ALTER trigger ttbregistro_setup_b02u for tbregistro_setup
active before update position 0
AS
begin
    
  if(old.datahora_inicio is distinct from new.datahora_inicio and new.datahora_inicio IS not null)then
  begin
    if(new.datahora_inicio > dateadd(minute, 5, current_timestamp))then
    begin
        exception "..." 'ERRO NA DATA DE INICIO. ('||formatdatetime(new.datahora_inicio)||' -> '||formatdatetime(current_date)||')';
    end
  end

  if(old.datahora_fim is distinct from new.datahora_fim and new.datahora_inicio IS not null)then
  begin
    if(new.datahora_fim < new.datahora_inicio)then
    begin
        exception "..." 'DATA FIM DO SETUP NAO PODE SER MENOR QUE A DATA DE INICIO. ('||formatdatetime(new.datahora_fim)||' -> '||formatdatetime(new.datahora_inicio)||')';
    end
  end

end
^

SET TERM ; ^

