-- dbo.ET_TabDokladyZbozi_HDC_D
CREATE TRIGGER dbo.ET_TabDokladyZbozi_HDC_D ON dbo.TabDokladyZbozi
WITH EXECUTE AS CALLER
FOR DELETE
AS
BEGIN
 SET NOCOUNT ON

-- !! trigger neupravujte, bude stejne pregenerovan pri startu pluginu PluginHDCRTN nebo Windows sluzby HDCDZApi !!

 DECLARE
  @id INT,
  @dpz TINYINT,
  @rada NVARCHAR(3),
  @sklad NVARCHAR(30)



 DECLARE c CURSOR LOCAL FAST_FORWARD FOR
  SELECT d.ID, d.DruhPohybuZbo, d.RadaDokladu, d.IDSklad
   FROM deleted d
 OPEN c
 WHILE (1=1)
  BEGIN
   FETCH NEXT FROM c INTO @id, @dpz, @rada, @sklad
   IF (@@FETCH_STATUS<>0) BREAK


-- sync informace pro reseni ASol/ProHolding/HDC
-- vydejky
   IF (@dpz=4)
    BEGIN
     IF OBJECT_ID(N'dbo._hdc_ph_PrijataJsonData', N'U') IS NOT NULL
      UPDATE dbo._hdc_ph_PrijataJsonData SET IDDoklad=NULL WHERE IDDoklad=@id

     IF OBJECT_ID(N'dbo._TabVyroba_Objednavky_Pol', N'U') IS NOT NULL
      BEGIN
       DELETE FROM dbo._TabVyroba_Objednavky_Pol WHERE IDDokladOZ=@id
       DELETE FROM dbo._TabVyroba_Objednavky WHERE IDDokladOZ=@id
      END
    END

   IF OBJECT_ID(N'dbo._hdc_PZ_PuvodniVC', N'U') IS NOT NULL
    DELETE FROM dbo._hdc_PZ_PuvodniVC WHERE IDDoklad=@id


  END
 CLOSE c
 DEALLOCATE c

END
