--
-- Host: localhost    Database: dbMatFiz
-- ------------------------------------------------------


use w;

delimiter ^

DROP TRIGGER IF EXISTS trgKontrahenci_BI;
CREATE TRIGGER trgKontrahenci_BI BEFORE INSERT ON tKontrahenci
  FOR EACH ROW 
  BEGIN
    SET NEW.cCT = CURRENT_TIMESTAMP;
    SET NEW.cTS = CURRENT_TIMESTAMP;
  END;
^

DROP TRIGGER IF EXISTS trgKontrahenci_BU;
CREATE TRIGGER trgKontrahenci_BU BEFORE UPDATE ON tKontrahenci
  FOR EACH ROW 
  BEGIN
    SET NEW.cTS = CURRENT_TIMESTAMP;
  END;
^


DROP TRIGGER IF EXISTS trgPrzechowalnia_BI;
CREATE TRIGGER trgPrzechowalnia_BI BEFORE INSERT ON tPrzechowalnia
  FOR EACH ROW 
  BEGIN
    declare vMax int;
    SET NEW.cCT = CURRENT_TIMESTAMP;
    SET NEW.cTS = CURRENT_TIMESTAMP;
    IF NEW.cDataPrzyjecia is null or NEW.cDataPrzyjecia = 0 THEN
        SET NEW.cDataPrzyjecia = curdate();
    END IF;
    IF NEW.cNumer is null or NEW.cNumer = 0 THEN
        select max(cNumer) into vMax from tPrzechowalnia;
        IF vMax is null or vMax = 0 THEN
            SET NEW.cNumer = 1;
        ELSE
            SET NEW.cNumer = vMax + 1;
        END IF;
    END IF;
    IF NEW.cCena is null or NEW.cCena = 0 THEN
        SET NEW.cCena = 40.00;
    END IF;
  END;
^  

DROP TRIGGER IF EXISTS trgPrzechowalnia_BU;
CREATE TRIGGER trgPrzechowalnia_BU BEFORE UPDATE ON tPrzechowalnia
  FOR EACH ROW 
  BEGIN
    SET NEW.cTS = CURRENT_TIMESTAMP;
  END;
^








