-- dbo.ET_TabVyrCP_HDC_D
CREATE TRIGGER dbo.ET_TabVyrCP_HDC_D ON dbo.TabVyrCP
WITH EXECUTE AS CALLER
FOR DELETE
AS
BEGIN
 SET NOCOUNT ON

-- !! trigger neupravujte, bude stejne pregenerovan pri startu pluginu PluginHDCRTN !!

 DECLARE
  @id INT,
  @idPZ INT,
  @idObjHlav INT,
  @idObjPol INT



 DECLARE c CURSOR LOCAL FAST_FORWARD FOR
  SELECT d.ID, d.IDPolozkaDokladu
   FROM deleted d
 OPEN c
 WHILE (1=1)
  BEGIN
   FETCH NEXT FROM c INTO @id, @idPZ
   IF (@@FETCH_STATUS<>0) BREAK


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


  END
 CLOSE c
 DEALLOCATE c




END