-- This file is part of the it-crafts software and is subject to copyright protection.
-- (C) 2024, All rights reserved by Steffen Anders, Elsteraue - Germany
-- Visit also https://www.it-crafts.de.
--

---------------------------------------------------------------------------------------------------
-- Aktualisierung der Bestandsbelege ohne BelTyp an den Detaildatensaetzen
UPDATE detail SET BelTyp = kopf.Typ
  FROM dbo.ut_LagerEinPos detail inner join dbo.ut_LagerEinKopf kopf on detail.BelTyp = '' AND detail.BelNr = kopf.BelNr
GO
UPDATE detail SET BelTyp = kopf.Typ
  FROM dbo.ut_LagerEinUst detail inner join dbo.ut_LagerEinKopf kopf on detail.BelTyp = '' AND detail.BelNr = kopf.BelNr
GO
-- Beleg mit der Nummer 0 anlegen, um ein Ziel für Aktualisierung des ersten Kopfes zu erzeugen
IF 0 = (SELECT COUNT(*) FROM ut_LagerEinKopf WHERE BelNr = 0 AND Typ = '')
  INSERT ut_LagerEinKopf (RecId, Typ, BelNr) VALUES(dbo.itcfunc_NextRecId_LagerEinKopf(), '', 0)
GO
UPDATE dbo.ut_LagerEinKopf SET KladLfdNr = -1 WHERE Typ = 'Z' AND TransNo <> '' AND KladLfdNr = 0
GO

---------------------------------------------------------------------------------------------------
-- Loeschtrigger
IF 0 < (SELECT COUNT(*) FROM sysobjects where [xtype] = 'TR' AND [name] = 'Tr_Del_LagerEinKopf')
  DROP TRIGGER Tr_Del_LagerEinKopf
GO
CREATE TRIGGER Tr_Del_LagerEinKopf ON dbo.ut_LagerEinKopf FOR DELETE
AS
  IF @@NESTLEVEL >= 10
    RETURN

  DELETE FROM dbo.ut_LagerEinPos WHERE RecId IN
    (SELECT X.RecId FROM dbo.ut_LagerEinPos X INNER JOIN DELETED D ON X.BelTyp = D.Typ AND X.BelNr = D.BelNr)
	
  DELETE FROM dbo.ut_LagerEinUst WHERE RecId IN
    (SELECT X.RecId FROM dbo.ut_LagerEinUst X INNER JOIN DELETED D ON X.BelTyp = D.Typ AND X.BelNr = D.BelNr)
GO
