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

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

 DECLARE
  @id INT,
  @sz NVARCHAR(3),
  @rc NVARCHAR(30),
  @idKZ INT,
  @sarze NVARCHAR(50)


 DECLARE c CURSOR LOCAL FAST_FORWARD FOR
  SELECT i.ID, i.SkupZbo, i.RegCis, i.IDKmenZbozi
   FROM inserted i
 OPEN c
 WHILE (1=1)
  BEGIN
   FETCH NEXT FROM c INTO @id, @sz, @rc, @idKZ
   IF (@@FETCH_STATUS<>0) BREAK
   
   IF (@idKZ IS NULL)
    BEGIN
     SET @idKZ = (SELECT ID FROM dbo.TabKmenZbozi WHERE SkupZbo=@sz AND RegCis=@rc)
     IF (@idKZ IS NOT NULL)
      UPDATE dbo._TabVyroba_Objednavky SET IDKmenZbozi=@idKZ WHERE ID=@id
    END
   
  END
 CLOSE c
 DEALLOCATE c

END
