-- update

set xact_abort on
go

begin transaction
go

set ANSI_NULLS on
go

/***************************************
* function dateToAsFormat
*
* converte le date da DATETIME al formato AS 8 cifre AAAAMMGG
*
* Steamware, S.E.L.
* mod: 2010.09.29
*
****************************************/
create FUNCTION dateToAsFormat
(
    @data DATETIME
)
RETURNS NVARCHAR(8)
AS
    BEGIN
        RETURN CONVERT(NVARCHAR(8), @data, 112)
    END
go

commit
go





set xact_abort on
go

begin transaction
go

alter table PosizioneUdcStorico drop
  constraint FK_PosizioneUdcStorico_ElencoCartellini 
go

exec sp_rename 'PK_PosizioneUdcStorico_1', 'tmp__PK_PosizioneUdcStorico_1', 'OBJECT'
go

exec sp_rename 'PosizioneUdcStorico', 'tmp__PosizioneUdcStorico_0', 'OBJECT'
go

create table PosizioneUdcStorico(
  UDC        nvarchar(50) not null,
  IdxCella   int          not null,
  DataInizio datetime     not null,
  CodCS      nchar(2)     not null,
  DataFine   datetime,

  constraint PK_PosizioneUdcStorico_1 primary key(UDC,IdxCella,DataInizio)
)
go

alter table PosizioneUdcStorico add
  constraint FK_PosizioneUdcStorico_ElencoCartellini foreign key(UDC) references ElencoCartellini(UDC) on update cascade
go

insert into PosizioneUdcStorico(UDC,IdxCella,DataInizio,CodCS,DataFine) select UDC,IdxCella,DataInizio,CodCS,DataFine from tmp__PosizioneUdcStorico_0
go

drop table tmp__PosizioneUdcStorico_0
go

commit
go


create index [<Name of Missing Index, sysname,>] on RilPro.RapQual(DataRapQual)
  include(nRapQual,CodFor,CodLega,Qta,BenesQual,UDC)
go


set xact_abort on
go

begin transaction
go

set ANSI_NULLS on
go

create VIEW v_RapQualSunto
AS
SELECT        TOP (100) PERCENT CAST(nRapQual AS NVARCHAR(20)) AS nRapQual, DataRapQual, CodFor, CodLega, SUM(Qta) AS Qta, BenesQual, COUNT(*) AS UdcTot, 
                         COUNT(UDC) AS UdcAssoc
FROM            RilPro.RapQual
GROUP BY nRapQual, DataRapQual, CodFor, CodLega, BenesQual
ORDER BY nRapQual
go

exec sp_addextendedproperty 'MS_DiagramPane1', '[0E232FF0-B466-11cf-A24F-00AA00A3EFFF, 1.00]
Begin DesignProperties = 
   Begin PaneConfigurations = 
      Begin PaneConfiguration = 0
         NumPanes = 4
         Configuration = "(H (1[40] 4[20] 2[20] 3) )"
      End
      Begin PaneConfiguration = 1
         NumPanes = 3
         Configuration = "(H (1 [50] 4 [25] 3))"
      End
      Begin PaneConfiguration = 2
         NumPanes = 3
         Configuration = "(H (1 [50] 2 [25] 3))"
      End
      Begin PaneConfiguration = 3
         NumPanes = 3
         Configuration = "(H (4 [30] 2 [40] 3))"
      End
      Begin PaneConfiguration = 4
         NumPanes = 2
         Configuration = "(H (1 [56] 3))"
      End
      Begin PaneConfiguration = 5
         NumPanes = 2
         Configuration = "(H (2 [66] 3))"
      End
      Begin PaneConfiguration = 6
         NumPanes = 2
         Configuration = "(H (4 [50] 3))"
      End
      Begin PaneConfiguration = 7
         NumPanes = 1
         Configuration = "(V (3))"
      End
      Begin PaneConfiguration = 8
         NumPanes = 3
         Configuration = "(H (1[56] 4[18] 2) )"
      End
      Begin PaneConfiguration = 9
         NumPanes = 2
         Configuration = "(H (1 [75] 4))"
      End
      Begin PaneConfiguration = 10
         NumPanes = 2
         Configuration = "(H (1[66] 2) )"
      End
      Begin PaneConfiguration = 11
         NumPanes = 2
         Configuration = "(H (4 [60] 2))"
      End
      Begin PaneConfiguration = 12
         NumPanes = 1
         Configuration = "(H (1) )"
      End
      Begin PaneConfiguration = 13
         NumPanes = 1
         Configuration = "(V (4))"
      End
      Begin PaneConfiguration = 14
         NumPanes = 1
         Configuration = "(V (2))"
      End
      ActivePaneConfig = 0
   End
   Begin DiagramPane = 
      Begin Origin = 
         Top = 0
         Left = 0
      End
      Begin Tables = 
         Begin Table = "RapQual (RilPro)"
            Begin Extent = 
               Top = 6
               Left = 38
               Bottom = 314
               Right = 208
            End
            DisplayFlags = 280
            TopColumn = 0
         End
      End
   End
   Begin SQLPane = 
   End
   Begin DataPane = 
      Begin ParameterDefaults = ""
      End
      Begin ColumnWidths = 9
         Width = 284
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
      End
   End
   Begin CriteriaPane = 
      Begin ColumnWidths = 12
         Column = 1440
         Alias = 1305
         Table = 1170
         Output = 720
         Append = 1400
         NewValue = 1170
         SortType = 1350
         SortOrder = 1410
         GroupBy = 1350
         Filter = 1350
         Or = 1350
         Or = 1350
         Or = 1350
      End
   End
End
', 'SCHEMA', 'dbo', 'VIEW', 'v_RapQualSunto'
go

exec sp_addextendedproperty 'MS_DiagramPaneCount', 1, 'SCHEMA', 'dbo', 'VIEW', 'v_RapQualSunto'
go

alter VIEW v_selMagLogico
AS
SELECT DISTINCT TOP (100) PERCENT CAST(IdxPosizione AS NVARCHAR(20)) AS value, 'Mag. ' + CAST(IdxPosizione AS NVARCHAR(20)) AS label, CodCS AS conditio
FROM            dbo.ElencoCartellini
WHERE        (IdxPosizione > 0)
ORDER BY label
go

commit
go


set xact_abort on
go

begin transaction
go

set ANSI_NULLS on
go

/***************************************
* STORED stp_batch_RapQual_S01
*
* Esegue lo step 1 (caricamento dati RAW da AS400) per la tab dei rapporti di qualità
*
* Steamware, S.E.L.
* mod: 2010.09.23
*
****************************************/
alter PROCEDURE BatchQueue.stp_batch_RapQual_S01
(
    @minData DATETIME
)
AS
    -- BOZZA DA COMPLETARE A CURA MAZZUCCONI!!!

    DECLARE @SQL AS NVARCHAR(1000)
    DECLARE @dataAs400 AS VARCHAR(8)
    
    SET @dataAs400 = (SELECT dbo.dateToAsFormat(@minData))

    -- svuoto tab raw attuale
    /*
    DELETE FROM RawData.XOGIX00F
    */


    -- INSERISCO DA AS400
    /*
    INSERT INTO RawData.XOGIX00F 
    (
        SET @SQL = 
        N'SELECT 
                XRPQLN
               ,XRPQLD
               ,XNRETI
               ,XCDFOR
               ,XCDTER
               ,XCDPAR
               ,XDTPRO
               ,XTRPRO
               ,XQTPRO
               ,XDESMT
               ,XMATSC
               ,XBENQL
        FROM OPENQUERY( P65220DC,  ''SELECT * FROM MAZZT_DTV3.XOGIX00F WHERE XRPQLD >= '
        SET @SQL = @SQL + @dataAs400 + ''' )'

        EXEC dbo.sp_executesql @SQL
    )
    */

RETURN
go

commit
go

set xact_abort on
go

begin transaction
go

set ANSI_NULLS on
go

/***************************************
* STORED stp_rappQualSuntoGetByDataRange
*
* Ottiene l'elenco dei record di rapp qualità di AS dato il range delle date
*
* Steamware, S.E.L.
* mod: 2010.09.29
*
****************************************/
create PROCEDURE stp_rappQualSuntoGetByDataRange
(
    @dataFrom DATETIME,
    @dataTo DATETIME
)
AS
    -- restituisce le righe richieste
    SELECT			*
        FROM        v_RapQualSunto
        WHERE		(DataRapQual > dbo.dateToAsFormat(@dataFrom)) AND (DataRapQual < dbo.dateToAsFormat(@dataTo))
        ORDER BY nRapQual
RETURN
go

/***************************************
* STORED stp_rappQualSuntoGetByNumRap
*
* Ottiene il record di rapp qualità di AS dato il numero del rapporto di qualità
*
* Steamware, S.E.L.
* mod: 2010.09.29
*
****************************************/
create PROCEDURE stp_rappQualSuntoGetByNumRap
(
    @nRapQual NVARCHAR(20)
)
AS
    -- restituisce le righe richieste
    SELECT			*
        FROM        v_RapQualSunto
        WHERE	(nRapQual = @nRapQual)
RETURN
go

/***************************************
* STORED stp_spostaUdc
*
* sposta un UDC, salvandone la posizione precedente (se esiste) nella tab storica
*
* Steamware, S.E.L.
* mod: 2010.06.11
*
****************************************/
alter PROCEDURE stp_spostaUdc
(
    @CodCS VARCHAR(2),
    @UDC VARCHAR(50),
    @IdxCellaTo INT
)
AS

BEGIN TRAN
    
    -- DICHIARAZIONI iniziali variabili
    DECLARE @IdxCellaFrom INT
    DECLARE @capienza INT
    DECLARE @numUdc INT
    
    -- controllo cella di partenza
    SET		@IdxCellaFrom = (SELECT IdxCella FROM PosizioneUdcCorrente WHERE UDC = @UDC)
    -- controllo se la cella di dest vada indicata come piena
    SET		@capienza = (
                            SELECT tc.Capienza 
                                FROM TipoCella TC INNER JOIN Celle c ON TC.IdxTipoCella=c.IdxTipoCella
                                WHERE c.IdxCella = @IdxCellaFrom	
                        )
    SET @numUdc = (SELECT COUNT(*) FROM PosizioneUdcCorrente WHERE IdxCella = @IdxCellaFrom)
    -- se capienza raggiunta aggiorno...
    IF(@numUdc -1 < @capienza)
        BEGIN
            EXEC stp_celle_updPiena @IdxCellaFrom, 0
        END
        
    -- cancello posizione occupata
    DELETE
    FROM	PosizioneUdcCorrente
    WHERE	UDC = @UDC
    
    -- creo una nuova posizione per l'UDC
    INSERT INTO PosizioneUdcCorrente(UDC, IdxCella, CodCS, DataRif)
    VALUES(@UDC, @IdxCellaTo, @CodCS, GETDATE())
    
    -- controllo se la cella di dest vada indicata come piena
    SET		@capienza = (
                            SELECT tc.Capienza 
                                FROM TipoCella TC INNER JOIN Celle c ON TC.IdxTipoCella=c.IdxTipoCella
                                WHERE c.IdxCella = @IdxCellaTo	
                        )
    SET @numUdc = (SELECT COUNT(*) FROM PosizioneUdcCorrente WHERE IdxCella = @IdxCellaTo)
    -- se capienza raggiunta aggiorno...
    IF(@numUdc >= @capienza)
        BEGIN
            EXEC stp_celle_updPiena @IdxCellaTo, 1
        END
    
COMMIT TRAN

RETURN
go

commit
go






-- registro versione...
INSERT INTO [dbo].[LogUpdateDb] ([Versione],[Data]) VALUES(265, GETDATE())
GO
