-- dbo.ET_Tabx_HDC_API_DigitalizaceSoubory_IU
CREATE TRIGGER dbo.ET_Tabx_HDC_API_DigitalizaceSoubory_IU ON dbo.Tabx_HDC_API_DigitalizaceSoubory
WITH EXECUTE AS CALLER
FOR INSERT, UPDATE
AS
BEGIN
 SET NOCOUNT ON

-- ! trigger neupravujte, bude stejne pregenerovan pri startu Win sluzby HDCDZApi

 DECLARE
  @id INT,
  @idDokl INT,
  @idDokum INT,
  @idZak INT



 DECLARE c CURSOR LOCAL FAST_FORWARD FOR
  SELECT i.ID, i.DocNumber, i.IDDokument
   FROM inserted i
 OPEN c
 WHILE (1=1)
  BEGIN
   FETCH NEXT FROM c INTO @id, @idDokl, @idDokum
   IF (@@FETCH_STATUS<>0) BREAK

   IF (@idDokum IS NOT NULL)
    BEGIN
     IF (@idDokl IS NOT NULL)
      IF EXISTS(SELECT 1 FROM dbo.TabDokladyZbozi WHERE ID=@idDokl)
       BEGIN
        IF NOT EXISTS(SELECT 1 FROM dbo.TabDokumVazba WHERE IdentVazby=9 AND IdTab=@idDokl AND IdDok=@idDokum)
         INSERT dbo.TabDokumVazba (IdentVazby, IdTab, IdDok) SELECT 9, @idDokl, @idDokum
       
        SET @idZak = (SELECT z.ID FROM dbo.TabDokladyZbozi d INNER JOIN dbo.TabZakazka z ON (z.CisloZakazky=d.CisloZakazky) WHERE d.ID=@idDokl)
        IF (@idZak IS NOT NULL)
         IF NOT EXISTS(SELECT 1 FROM dbo.TabDokumVazba WHERE IdentVazby=2 AND IdTab=@idZak AND IdDok=@idDokum)
          INSERT dbo.TabDokumVazba (IdentVazby, IdTab, IdDok) SELECT 2, @idZak, @idDokum       
       END -- doklad existuje
    END -- dokument neni null


  END
 CLOSE c
 DEALLOCATE c
  

END
