-- dbo.ET_TabPohybyZbozi_HDC_IU
CREATE TRIGGER dbo.ET_TabPohybyZbozi_HDC_IU ON dbo.TabPohybyZbozi
WITH EXECUTE AS CALLER
FOR INSERT,UPDATE
AS
BEGIN
 SET NOCOUNT ON
 
-- !! trigger neupravujte, bude stejne pregenerovan pri startu pluginu PluginHDCRTN nebo slozby HDCDZApi !!

 DECLARE
  @id INT,
  @dpz TINYINT,
  @mnoz NUMERIC(19,6),
  @idObjHlav INT,
  @idObjPol INT



 DECLARE c CURSOR LOCAL FAST_FORWARD FOR
  SELECT i.ID, i.DruhPohybuZbo, i.Mnozstvi
   FROM inserted i
 OPEN c
 WHILE (1=1)
  BEGIN
   FETCH NEXT FROM c INTO @id, @dpz, @mnoz
   IF (@@FETCH_STATUS<>0) BREAK


-- sync informace pro reseni ASol/ProHolding/HDC
   IF (@dpz=4)
    BEGIN
     IF UPDATE(Mnozstvi)
      BEGIN
       IF OBJECT_ID(N'dbo._TabVyroba_Objednavky_Pol', N'U') IS NOT NULL
        BEGIN
         SELECT @idObjHlav=IDHlava, @idObjPol=ID FROM dbo._TabVyroba_Objednavky_Pol WHERE IDPohybOZ=@id
         UPDATE dbo._TabVyroba_Objednavky_Pol SET Mnozstvi=@mnoz WHERE ID=@idObjPol
         IF OBJECT_ID(N'dbo._TabVyroba_Objednavky', N'U') IS NOT NULL
          UPDATE dbo._TabVyroba_Objednavky SET MnozVydane=ISNULL( (SELECT SUM(Mnozstvi) FROM dbo._TabVyroba_Objednavky_Pol WHERE IDHlava=@idObjHlav), 0) WHERE ID=@idObjHlav
        END
      END
    END


  END
 CLOSE c
 DEALLOCATE c

END
