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

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

 DECLARE
  @id INT,
  @idPZ INT,
  @idKmen INT



 DECLARE c CURSOR LOCAL FAST_FORWARD FOR
  SELECT i.ID, i.IDPohybZbozi, i.IDKmenZbozi
   FROM inserted i
 OPEN c
 WHILE (1=1)
  BEGIN
   FETCH NEXT FROM c INTO @id, @idPZ, @idKmen
   IF (@@FETCH_STATUS<>0) BREAK

   IF (@idKmen IS NULL)
    BEGIN
     SELECT @idKmen=s.IDKmenZbozi FROM dbo.TabPoybyZbozi p INNER JOIN dbo.TabStavSkladu s ON (s.ID=p.IDZboSklad) WHERE p.ID=@idPZ
     UPDATE dbo._TabVyroba_VydejMatSarze SET IDKmenZbozi=@idKmen WHERE ID=@id
    END


  END
 CLOSE c
 DEALLOCATE c

END
