SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE OR ALTER PROCEDURE [dbo].[sp_xExePackingListPallet] @IDOperatore int, @Documento varchar(8), @Azione char(1) = 'P', -- 'P' = Prenota, 'S' = S-prenota @RC int OUTPUT AS BEGIN SET NOCOUNT ON; SET @RC = 0; DECLARE @Nominativo varchar(50); DECLARE @DocumentoPrenotato bit = 0; DECLARE @Description varchar(255) = ''; DECLARE @Message varchar(255) = ''; DECLARE @IDResult int = 0; DECLARE @ID int = 0; DECLARE @Code varchar(64) = @Documento; SELECT @Nominativo = [Login] FROM dbo.Operatori WHERE ID = @IDOperatore; IF @Azione NOT IN ('P', 'S') BEGIN SET @RC = -10; RETURN; END; DECLARE @TargetCelle TABLE ( IDCella int PRIMARY KEY ); INSERT INTO @TargetCelle (IDCella) SELECT DISTINCT Cella FROM dbo.XMag_ViewPackingList WHERE Documento = @Documento AND Cella IS NOT NULL; IF NOT EXISTS (SELECT 1 FROM @TargetCelle) BEGIN SET @RC = -20; RETURN; END; IF EXISTS ( SELECT 1 FROM dbo.XMag_ViewPackingList WHERE Documento = @Documento AND ISNULL(IDStato, 0) = 1 ) BEGIN SET @DocumentoPrenotato = 1; END; IF @Azione = 'P' BEGIN -- Gia' prenotata: nessuna variazione IF @DocumentoPrenotato = 1 RETURN; -- Azzera la prenotazione di tutti gli altri documenti UPDATE c SET c.IDStato = 0, c.ModUtente = @Nominativo, c.ModDataOra = GETDATE() FROM dbo.Celle c WHERE c.ID IN ( SELECT DISTINCT Cella FROM dbo.XMag_ViewPackingList WHERE ISNULL(IDStato, 0) = 1 AND Documento <> @Documento AND Cella IS NOT NULL ); -- Prenota soltanto le celle del documento target UPDATE c SET c.IDStato = 1, c.ModUtente = @Nominativo, c.ModDataOra = GETDATE() FROM dbo.Celle c INNER JOIN @TargetCelle t ON t.IDCella = c.ID; SELECT TOP 1 @Description = NAZIONE FROM dbo.XMag_ViewPackingList WHERE Documento = @Documento; EXECUTE @RC = [dbo].[sp_LogPackingList] @ID ,@Code ,@Description ,@Message OUTPUT ,@IDResult OUTPUT; RETURN; END; IF @Azione = 'S' BEGIN -- Gia' non prenotata: nessuna variazione IF @DocumentoPrenotato = 0 RETURN; -- Togli la prenotazione soltanto al documento target UPDATE c SET c.IDStato = 0, c.ModUtente = @Nominativo, c.ModDataOra = GETDATE() FROM dbo.Celle c INNER JOIN @TargetCelle t ON t.IDCella = c.ID; RETURN; END; END; GO