CREATE TABLE TBTRIGGER_STATUS (
    ID INTEGER NOT NULL,
    "TRIGGER" VARCHAR(50),
    STATUS INTEGER);

ALTER TABLE TBTRIGGER_STATUS
ADD CONSTRAINT PK_TBTRIGGER_STATUS
PRIMARY KEY (ID);

CREATE SEQUENCE GTBTRIGGER_STATUS;

create trigger ttbtrigger_status_b01i for tbtrigger_status
active before insert position 0
as
begin
  if (new.id is null) then
    new.id = gen_id(GTBTRIGGER_STATUS,1);
end;

CREATE OR ALTER procedure sp_trigger_acti_inac (
    tabela varchar(31),
    status integer = 0,
    gravar integer = 0)
returns (
    sql blob sub_type 1 segment size 80,
    trigger_name varchar(50),
    trigger_status integer)
as
begin

  for
    select 
        trim(RDB$TRIGGER_NAME),
        'alter trigger '|| trim(RDB$TRIGGER_NAME)||' '||iif(:STATUS = 0, 'inactive;', iif(:STATUS = 1, 'active;',
            coalesce((select first 1 iif(s.STATUS = 1, 'active;', 'inactive;') from tbtrigger_status s where s."TRIGGER" = trim(RDB$TRIGGER_NAME)),'active;')
        )) as SQL,
        iif(RDB$TRIGGER_INACTIVE = 1,0,1)
    from RDB$TRIGGERS t where t.rdb$relation_name = upper(:TABELA)
  into
    :TRIGGER_NAME,
    :SQL,
    :TRIGGER_STATUS
  do begin

    if(GRAVAR = 1 and STATUS < 3)then
    begin
        UPDATE OR INSERT INTO TBTRIGGER_STATUS ("TRIGGER", STATUS)
                                VALUES (:TRIGGER_NAME, :TRIGGER_STATUS)
                              MATCHING ("TRIGGER");

    end
    
    EXECUTE STATEMENT :SQL;
    suspend;
  end
    
end;


COMMENT ON PARAMETER SP_TRIGGER_ACTI_INAC.STATUS IS
'0-inativar, 1-ativar';



