﻿/*
Deployment script for C2P_DB

This code was generated by a tool.
Changes to this file may cause incorrect behavior and will be lost if
the code is regenerated.
*/

GO
SET ANSI_NULLS, ANSI_PADDING, ANSI_WARNINGS, ARITHABORT, CONCAT_NULL_YIELDS_NULL, QUOTED_IDENTIFIER ON;

SET NUMERIC_ROUNDABORT OFF;


GO
:setvar DatabaseName "C2P_DB"
:setvar DefaultFilePrefix "C2P_DB"
:setvar DefaultDataPath ""
:setvar DefaultLogPath ""

GO
:on error exit
GO
/*
Detect SQLCMD mode and disable script execution if SQLCMD mode is not supported.
To re-enable the script after enabling SQLCMD mode, execute the following:
SET NOEXEC OFF; 
*/
:setvar __IsSqlCmdEnabled "True"
GO
IF N'$(__IsSqlCmdEnabled)' NOT LIKE N'True'
    BEGIN
        PRINT N'SQLCMD mode must be enabled to successfully execute this script.';
        SET NOEXEC ON;
    END


GO
USE [master];


GO

IF (DB_ID(N'$(DatabaseName)') IS NOT NULL) 
BEGIN
    ALTER DATABASE [$(DatabaseName)]
    SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
    DROP DATABASE [$(DatabaseName)];
END

GO
PRINT N'Creating $(DatabaseName)...'
GO
CREATE DATABASE [$(DatabaseName)] COLLATE SQL_Latin1_General_CP1_CI_AS
GO
IF EXISTS (SELECT 1
           FROM   [master].[dbo].[sysdatabases]
           WHERE  [name] = N'$(DatabaseName)')
    BEGIN
        ALTER DATABASE [$(DatabaseName)]
            SET ANSI_NULLS ON,
                ANSI_PADDING ON,
                ANSI_WARNINGS ON,
                ARITHABORT ON,
                CONCAT_NULL_YIELDS_NULL ON,
                NUMERIC_ROUNDABORT OFF,
                QUOTED_IDENTIFIER ON,
                ANSI_NULL_DEFAULT ON,
                CURSOR_DEFAULT LOCAL,
                RECOVERY FULL,
                CURSOR_CLOSE_ON_COMMIT OFF,
                AUTO_CREATE_STATISTICS ON,
                AUTO_SHRINK OFF,
                AUTO_UPDATE_STATISTICS ON,
                RECURSIVE_TRIGGERS OFF 
            WITH ROLLBACK IMMEDIATE;
        ALTER DATABASE [$(DatabaseName)]
            SET AUTO_CLOSE OFF 
            WITH ROLLBACK IMMEDIATE;
    END


GO
IF EXISTS (SELECT 1
           FROM   [master].[dbo].[sysdatabases]
           WHERE  [name] = N'$(DatabaseName)')
    BEGIN
        ALTER DATABASE [$(DatabaseName)]
            SET ALLOW_SNAPSHOT_ISOLATION OFF;
    END


GO
IF EXISTS (SELECT 1
           FROM   [master].[dbo].[sysdatabases]
           WHERE  [name] = N'$(DatabaseName)')
    BEGIN
        ALTER DATABASE [$(DatabaseName)]
            SET READ_COMMITTED_SNAPSHOT OFF 
            WITH ROLLBACK IMMEDIATE;
    END


GO
IF EXISTS (SELECT 1
           FROM   [master].[dbo].[sysdatabases]
           WHERE  [name] = N'$(DatabaseName)')
    BEGIN
        ALTER DATABASE [$(DatabaseName)]
            SET AUTO_UPDATE_STATISTICS_ASYNC OFF,
                PAGE_VERIFY NONE,
                DATE_CORRELATION_OPTIMIZATION OFF,
                DISABLE_BROKER,
                PARAMETERIZATION SIMPLE,
                SUPPLEMENTAL_LOGGING OFF 
            WITH ROLLBACK IMMEDIATE;
    END


GO
IF IS_SRVROLEMEMBER(N'sysadmin') = 1
    BEGIN
        IF EXISTS (SELECT 1
                   FROM   [master].[dbo].[sysdatabases]
                   WHERE  [name] = N'$(DatabaseName)')
            BEGIN
                EXECUTE sp_executesql N'ALTER DATABASE [$(DatabaseName)]
    SET TRUSTWORTHY OFF,
        DB_CHAINING OFF 
    WITH ROLLBACK IMMEDIATE';
            END
    END
ELSE
    BEGIN
        PRINT N'The database settings cannot be modified. You must be a SysAdmin to apply these settings.';
    END


GO
IF IS_SRVROLEMEMBER(N'sysadmin') = 1
    BEGIN
        IF EXISTS (SELECT 1
                   FROM   [master].[dbo].[sysdatabases]
                   WHERE  [name] = N'$(DatabaseName)')
            BEGIN
                EXECUTE sp_executesql N'ALTER DATABASE [$(DatabaseName)]
    SET HONOR_BROKER_PRIORITY OFF 
    WITH ROLLBACK IMMEDIATE';
            END
    END
ELSE
    BEGIN
        PRINT N'The database settings cannot be modified. You must be a SysAdmin to apply these settings.';
    END


GO
USE [$(DatabaseName)];


GO
IF fulltextserviceproperty(N'IsFulltextInstalled') = 1
    EXECUTE sp_fulltext_database 'enable';


GO
PRINT N'Creating [tmp]...';


GO
CREATE SCHEMA [tmp]
    AUTHORIZATION [dbo];


GO
PRINT N'Creating [voc]...';


GO
CREATE SCHEMA [voc]
    AUTHORIZATION [dbo];


GO
PRINT N'Creating [ext]...';


GO
CREATE SCHEMA [ext]
    AUTHORIZATION [dbo];


GO
PRINT N'Creating [dbo].[Vocabolario]...';


GO
CREATE TABLE [dbo].[Vocabolario] (
    [Lingua]     NVARCHAR (3)   NOT NULL,
    [Lemma]      NVARCHAR (50)  NOT NULL,
    [Traduzione] NVARCHAR (500) NOT NULL,
    CONSTRAINT [PK_Vocabolario] PRIMARY KEY CLUSTERED ([Lingua] ASC, [Lemma] ASC)
);


GO
PRINT N'Creating [dbo].[Vocabolario].[I_lemma]...';


GO
CREATE NONCLUSTERED INDEX [I_lemma]
    ON [dbo].[Vocabolario]([Lemma] ASC);


GO
PRINT N'Creating [dbo].[Lingue]...';


GO
CREATE TABLE [dbo].[Lingue] (
    [Lingua]            NVARCHAR (3)  NOT NULL,
    [DescrizioneLingua] NVARCHAR (50) NOT NULL,
    CONSTRAINT [PK_Lingue] PRIMARY KEY CLUSTERED ([Lingua] ASC)
);


GO
PRINT N'Creating [dbo].[Config]...';


GO
CREATE TABLE [dbo].[Config] (
    [Parameter] NVARCHAR (50) NOT NULL,
    [Value]     NVARCHAR (50) NULL,
    CONSTRAINT [PK_Config] PRIMARY KEY CLUSTERED ([Parameter] ASC)
);


GO
PRINT N'Creating [dbo].[QuoteOC]...';


GO
CREATE TABLE [dbo].[QuoteOC] (
    [QuoteType]  CHAR (1)        NOT NULL,
    [CodQuote]   BIGINT          NOT NULL,
    [QuoteRev]   INT             NOT NULL,
    [NumEx]      INT             NOT NULL,
    [ProcessNum] NVARCHAR (50)   NOT NULL,
    [CodPlant]   NVARCHAR (50)   NOT NULL,
    [Class01]    NVARCHAR (50)   NOT NULL,
    [Class02]    NVARCHAR (50)   NOT NULL,
    [Class03]    NVARCHAR (50)   NOT NULL,
    [Class04]    NVARCHAR (50)   NOT NULL,
    [Class05]    NVARCHAR (50)   NOT NULL,
    [TotQty]     DECIMAL (18, 6) NOT NULL,
    [TotCost]    DECIMAL (18, 6) NOT NULL,
    [Quota]      DECIMAL (18, 6) NOT NULL,
    [C4UG]       AS              (([TotCost] * [Quota]) / [TotQty]) PERSISTED,
    [valid]      BIT             NOT NULL,
    CONSTRAINT [PK_QuoteExtra] PRIMARY KEY CLUSTERED ([QuoteType] ASC, [CodQuote] ASC, [QuoteRev] ASC, [NumEx] ASC)
);


GO
PRINT N'Creating [dbo].[QuoteWorkExt]...';


GO
CREATE TABLE [dbo].[QuoteWorkExt] (
    [QuoteType] CHAR (1)       NOT NULL,
    [CodQuote]  BIGINT         NOT NULL,
    [QuoteRev]  INT            NOT NULL,
    [NumWE]     INT            NOT NULL,
    [EWC4UG]    DECIMAL (9, 6) NOT NULL,
    [UM]        NVARCHAR (50)  NOT NULL,
    [valid]     BIT            NOT NULL,
    CONSTRAINT [PK_QuoteWorkExt] PRIMARY KEY CLUSTERED ([QuoteRev] ASC, [QuoteType] ASC, [CodQuote] ASC, [NumWE] ASC)
);


GO
PRINT N'Creating [dbo].[Package2Item]...';


GO
CREATE TABLE [dbo].[Package2Item] (
    [CodItem]   NVARCHAR (50)   NOT NULL,
    [CodPackag] NVARCHAR (50)   NOT NULL,
    [TotQta]    DECIMAL (18, 3) NOT NULL,
    [Weight]    DECIMAL (9, 4)  NOT NULL,
    [Tare]      DECIMAL (9, 4)  NOT NULL,
    [NumImb]    DECIMAL (9, 6)  NOT NULL,
    [Durata]    DECIMAL (18, 6) NOT NULL,
    CONSTRAINT [PK_Package2Item] PRIMARY KEY CLUSTERED ([CodItem] ASC, [CodPackag] ASC)
);


GO
PRINT N'Creating [dbo].[QuoteFull_Q_old]...';


GO
CREATE TABLE [dbo].[QuoteFull_Q_old] (
    [Vers]            VARCHAR (5)      NOT NULL,
    [QuoteType]       CHAR (1)         NOT NULL,
    [CodQuote]        BIGINT           NOT NULL,
    [QuoteRev]        INT              NOT NULL,
    [CodClient]       NVARCHAR (50)    NOT NULL,
    [ClientName]      NVARCHAR (250)   NOT NULL,
    [CodItem]         NVARCHAR (50)    NOT NULL,
    [CodItemGroup]    NVARCHAR (50)    NOT NULL,
    [RawMat]          NVARCHAR (50)    NOT NULL,
    [UnitWeight]      DECIMAL (9, 3)   NOT NULL,
    [BatchQty]        INT              NOT NULL,
    [CodInco]         NVARCHAR (5)     NOT NULL,
    [KeyAM]           NVARCHAR (101)   NOT NULL,
    [Note]            NVARCHAR (2500)  NOT NULL,
    [FullCost]        DECIMAL (9, 6)   NOT NULL,
    [MinPrice]        DECIMAL (9, 6)   NOT NULL,
    [PriceOff]        DECIMAL (9, 6)   NOT NULL,
    [CodClientAssoc]  NVARCHAR (100)   NULL,
    [ClientNameAssoc] NVARCHAR (100)   NULL,
    [ItemDescr]       NVARCHAR (100)   NULL,
    [CodifProfilo]    NVARCHAR (100)   NULL,
    [ClasseMerc]      NVARCHAR (100)   NULL,
    [TipoDies]        NVARCHAR (100)   NULL,
    [CodDiesGroup]    NVARCHAR (100)   NULL,
    [DiamDies]        NVARCHAR (100)   NULL,
    [HoleNumDies]     NVARCHAR (100)   NULL,
    [DiesPrice]       NVARCHAR (100)   NULL,
    [DiesExpLife]     NVARCHAR (100)   NULL,
    [DiesEOLife]      NVARCHAR (100)   NULL,
    [NumDiesInList]   NVARCHAR (100)   NULL,
    [NumDiesExaust]   NVARCHAR (100)   NULL,
    [CodPlant]        NVARCHAR (100)   NULL,
    [KeyAMIL]         NVARCHAR (100)   NULL,
    [KgTeo]           NVARCHAR (100)   NULL,
    [NumSMED]         NVARCHAR (100)   NULL,
    [QuotaMan]        NVARCHAR (100)   NULL,
    [PRMWeight]       NVARCHAR (100)   NULL,
    [PWeight]         NVARCHAR (100)   NULL,
    [PTare]           NVARCHAR (100)   NULL,
    [LivPackage]      NVARCHAR (100)   NULL,
    [LivPackageDett]  NVARCHAR (100)   NULL,
    [RawMatCost]      DECIMAL (18, 6)  NOT NULL,
    [RawMatExtraCost] DECIMAL (18, 6)  NOT NULL,
    [RawMatFullCost]  DECIMAL (19, 6)  NULL,
    [CodPackag]       NVARCHAR (50)    NOT NULL,
    [PkgDesc]         NVARCHAR (100)   NULL,
    [FSR]             DECIMAL (27, 19) NULL,
    [ProvvCost]       DECIMAL (38, 7)  NOT NULL,
    [EECost]          DECIMAL (38, 7)  NOT NULL,
    [GasCost]         DECIMAL (38, 7)  NOT NULL,
    [DiesCost]        DECIMAL (38, 7)  NOT NULL,
    [PackCost]        DECIMAL (38, 7)  NOT NULL,
    [TranspCost]      DECIMAL (38, 7)  NOT NULL,
    [SellCost01]      DECIMAL (38, 7)  NOT NULL,
    [RefCost01]       DECIMAL (38, 7)  NOT NULL,
    [SellCost04]      DECIMAL (38, 7)  NOT NULL,
    [RefCost04]       DECIMAL (38, 7)  NOT NULL,
    [WSR01]           DECIMAL (9, 8)   NOT NULL,
    [MSR01]           DECIMAL (9, 8)   NOT NULL,
    [NetProd01]       DECIMAL (9, 3)   NOT NULL,
    [FC4UG01]         DECIMAL (9, 6)   NOT NULL,
    [VC4UG01]         DECIMAL (9, 6)   NOT NULL,
    [OH4UG01]         DECIMAL (9, 6)   NOT NULL,
    [SC4UG01]         DECIMAL (9, 6)   NOT NULL,
    [DSR]             DECIMAL (38, 27) NULL,
    [NetProd04]       DECIMAL (9, 3)   NOT NULL,
    [FC4UG04]         DECIMAL (9, 6)   NOT NULL,
    [VC4UG04]         DECIMAL (9, 6)   NOT NULL,
    [FVC]             DECIMAL (38, 7)  NULL,
    [Charge]          DECIMAL (9, 6)   NOT NULL
);


GO
PRINT N'Creating [dbo].[Package2ItemClient]...';


GO
CREATE TABLE [dbo].[Package2ItemClient] (
    [CodItem]   NVARCHAR (50)   NOT NULL,
    [CodClient] NVARCHAR (50)   NOT NULL,
    [CodPackag] NVARCHAR (50)   NOT NULL,
    [TotQta]    DECIMAL (18, 3) NOT NULL,
    [Weight]    DECIMAL (18, 6) NOT NULL,
    [Tare]      DECIMAL (18, 6) NOT NULL,
    [NumImb]    DECIMAL (9, 6)  NOT NULL,
    [Durata]    DECIMAL (18, 6) NOT NULL,
    CONSTRAINT [PK_Package2ItemClient] PRIMARY KEY CLUSTERED ([CodItem] ASC, [CodClient] ASC, [CodPackag] ASC)
);


GO
PRINT N'Creating [dbo].[PackagDet]...';


GO
CREATE TABLE [dbo].[PackagDet] (
    [CodPackag]  NVARCHAR (50)  NOT NULL,
    [PackagDesc] NVARCHAR (250) NOT NULL,
    [RMCost]     DECIMAL (9, 3) NOT NULL,
    [RMWeight]   DECIMAL (9, 4) NOT NULL,
    CONSTRAINT [PK_PackagDet] PRIMARY KEY CLUSTERED ([CodPackag] ASC)
);


GO
PRINT N'Creating [dbo].[TabImbArt]...';


GO
CREATE TABLE [dbo].[TabImbArt] (
    [KeyA]   NVARCHAR (50)   NOT NULL,
    [NumImb] DECIMAL (9, 6)  NOT NULL,
    [TotOut] DECIMAL (18, 6) NOT NULL,
    [Durata] DECIMAL (18, 6) NOT NULL,
    CONSTRAINT [PK_TabImbArt] PRIMARY KEY CLUSTERED ([KeyA] ASC)
);


GO
PRINT N'Creating [dbo].[PlantsDet]...';


GO
CREATE TABLE [dbo].[PlantsDet] (
    [CodPlant] NVARCHAR (50)  NOT NULL,
    [Descript] NVARCHAR (250) NOT NULL,
    [Charge]   DECIMAL (9, 6) NOT NULL,
    CONSTRAINT [PK_PlantsDet] PRIMARY KEY CLUSTERED ([CodPlant] ASC)
);


GO
PRINT N'Creating [dbo].[RevHistory]...';


GO
CREATE TABLE [dbo].[RevHistory] (
    [RevType]     NVARCHAR (50)  NOT NULL,
    [RevNum]      INT            NOT NULL,
    [DateRev]     DATETIME       NOT NULL,
    [Description] NVARCHAR (250) NOT NULL,
    CONSTRAINT [PK_RevHistory] PRIMARY KEY CLUSTERED ([RevType] ASC, [RevNum] ASC)
);


GO
PRINT N'Creating [dbo].[DiesGroupDet]...';


GO
CREATE TABLE [dbo].[DiesGroupDet] (
    [CodDiesGroup] NVARCHAR (50)  NOT NULL,
    [Price]        DECIMAL (9, 3) NOT NULL,
    [QtyTot]       INT            NOT NULL,
    [QtyEOL]       INT            NOT NULL,
    [ExpLife]      DECIMAL (9, 2) NOT NULL,
    [EOLLife]      DECIMAL (9, 2) NOT NULL,
    [DateMod]      DATE           NULL,
    [UserMod]      NVARCHAR (50)  NULL,
    CONSTRAINT [PK_DiesGroupDet] PRIMARY KEY CLUSTERED ([CodDiesGroup] ASC)
);


GO
PRINT N'Creating [dbo].[Cost2Plant]...';


GO
CREATE TABLE [dbo].[Cost2Plant] (
    [CodPlant]      NVARCHAR (50)  NOT NULL,
    [ProcessNum]    NVARCHAR (50)  NOT NULL,
    [FC]            DECIMAL (9, 4) NOT NULL,
    [VC]            DECIMAL (9, 4) NOT NULL,
    [OH]            DECIMAL (9, 4) NOT NULL,
    [SC]            DECIMAL (9, 4) NOT NULL,
    [QuotaPlantStd] DECIMAL (9, 4) NOT NULL,
    [QuotaManStd]   DECIMAL (9, 4) NOT NULL,
    CONSTRAINT [PK_Cost2Plant] PRIMARY KEY CLUSTERED ([CodPlant] ASC, [ProcessNum] ASC)
);


GO
PRINT N'Creating [dbo].[ClientDet]...';


GO
CREATE TABLE [dbo].[ClientDet] (
    [CodClient]  NVARCHAR (50)  NOT NULL,
    [ClientName] NVARCHAR (250) NOT NULL,
    [CodAg]      NVARCHAR (50)  NOT NULL,
    [ZipCode]    NVARCHAR (50)  NOT NULL,
    [City]       NVARCHAR (50)  NOT NULL,
    [State]      NVARCHAR (50)  NOT NULL,
    [Nation]     NVARCHAR (50)  NOT NULL,
    [TranspZone] NVARCHAR (50)  NULL,
    CONSTRAINT [PK_ClientDet] PRIMARY KEY CLUSTERED ([CodClient] ASC)
);


GO
PRINT N'Creating [dbo].[AgentsDet]...';


GO
CREATE TABLE [dbo].[AgentsDet] (
    [CodAg]        NVARCHAR (50)  NOT NULL,
    [Lastname]     NVARCHAR (50)  NOT NULL,
    [Firstname]    NVARCHAR (50)  NOT NULL,
    [QuotaProvvAg] DECIMAL (9, 6) NOT NULL,
    CONSTRAINT [PK_AgentsDet] PRIMARY KEY CLUSTERED ([CodAg] ASC)
);


GO
PRINT N'Creating [dbo].[Utilities]...';


GO
CREATE TABLE [dbo].[Utilities] (
    [CodUtil]  NVARCHAR (50)  NOT NULL,
    [CodPlant] NVARCHAR (50)  NOT NULL,
    [UnitCost] DECIMAL (9, 6) NOT NULL,
    CONSTRAINT [PK_Utilities] PRIMARY KEY CLUSTERED ([CodUtil] ASC, [CodPlant] ASC)
);


GO
PRINT N'Creating [dbo].[Incoterms]...';


GO
CREATE TABLE [dbo].[Incoterms] (
    [CodInco]  NVARCHAR (5)   NOT NULL,
    [Descript] NVARCHAR (250) NOT NULL,
    [HasTC]    INT            NOT NULL,
    CONSTRAINT [PK_Incoterms] PRIMARY KEY CLUSTERED ([CodInco] ASC)
);


GO
PRINT N'Creating [dbo].[TranspCostDet]...';


GO
CREATE TABLE [dbo].[TranspCostDet] (
    [TranspZone] NVARCHAR (50)  NOT NULL,
    [TranspCost] DECIMAL (9, 6) NOT NULL,
    CONSTRAINT [PK_TranspCostDet_1] PRIMARY KEY CLUSTERED ([TranspZone] ASC)
);


GO
PRINT N'Creating [dbo].[QuoteRM]...';


GO
CREATE TABLE [dbo].[QuoteRM] (
    [QuoteType]       CHAR (1)        NOT NULL,
    [CodQuote]        BIGINT          NOT NULL,
    [QuoteRev]        INT             NOT NULL,
    [NumRM]           INT             NOT NULL,
    [RawMat]          NVARCHAR (50)   NOT NULL,
    [RawMatCost]      DECIMAL (18, 6) NOT NULL,
    [RawMatExtraCost] DECIMAL (18, 6) NOT NULL,
    [CodPackag]       NVARCHAR (50)   NOT NULL,
    [FCR]             DECIMAL (18, 6) NOT NULL,
    [FYR]             AS              ((1) / [FCR]),
    [FSR]             AS              ((1) - (1) / [FCR]),
    [valid]           BIT             NOT NULL,
    CONSTRAINT [PK_QuoteRM] PRIMARY KEY CLUSTERED ([QuoteType] ASC, [CodQuote] ASC, [QuoteRev] ASC, [NumRM] ASC)
);


GO
PRINT N'Creating [dbo].[ItemDet]...';


GO
CREATE TABLE [dbo].[ItemDet] (
    [CodItem]      NVARCHAR (50)  NOT NULL,
    [ItemDescr]    NVARCHAR (250) NOT NULL,
    [CodPlant]     NVARCHAR (50)  NOT NULL,
    [UnitWeight]   DECIMAL (9, 3) NOT NULL,
    [CodItemGroup] NVARCHAR (50)  NOT NULL,
    [Class01]      NVARCHAR (50)  NOT NULL,
    [Class02]      NVARCHAR (50)  NOT NULL,
    [Class03]      NVARCHAR (50)  NOT NULL,
    [Class04]      NVARCHAR (50)  NOT NULL,
    [Class05]      NVARCHAR (50)  NOT NULL,
    CONSTRAINT [PK_AnagArticoli] PRIMARY KEY CLUSTERED ([CodItem] ASC)
);


GO
PRINT N'Creating [dbo].[Package2]...';


GO
CREATE TABLE [dbo].[Package2] (
    [CodPackag] NVARCHAR (50)   NOT NULL,
    [TotQta]    DECIMAL (18, 3) NOT NULL,
    [Weight]    DECIMAL (18, 6) NOT NULL,
    [Tare]      DECIMAL (18, 6) NOT NULL,
    [NumImb]    DECIMAL (9, 6)  NOT NULL,
    [Durata]    DECIMAL (18, 6) NOT NULL,
    CONSTRAINT [PK_Package2] PRIMARY KEY CLUSTERED ([CodPackag] ASC)
);


GO
PRINT N'Creating [dbo].[TabImbGrp]...';


GO
CREATE TABLE [dbo].[TabImbGrp] (
    [CodPackag] NVARCHAR (50)   NOT NULL,
    [NumImb]    DECIMAL (9, 6)  NOT NULL,
    [TotOut]    DECIMAL (18, 6) NOT NULL,
    [Durata]    DECIMAL (18, 6) NOT NULL,
    CONSTRAINT [PK_TabImbGrp] PRIMARY KEY CLUSTERED ([CodPackag] ASC)
);


GO
PRINT N'Creating [dbo].[Permessi]...';


GO
CREATE TABLE [dbo].[Permessi] (
    [COD_PERMESSO] VARCHAR (50)  NOT NULL,
    [URL]          VARCHAR (250) NOT NULL,
    [GRUPPO]       INT           NULL,
    [NUMERO]       INT           NULL,
    [NOME]         VARCHAR (50)  NULL,
    [DESCRIZIONE]  VARCHAR (50)  NULL,
    CONSTRAINT [PK_Permessi] PRIMARY KEY CLUSTERED ([COD_PERMESSO] ASC)
);


GO
PRINT N'Creating [dbo].[Permessi2Funzione]...';


GO
CREATE TABLE [dbo].[Permessi2Funzione] (
    [COD_PERMESSO] VARCHAR (50)  NOT NULL,
    [COD_FUNZIONE] NVARCHAR (31) NOT NULL,
    [READWRITE]    CHAR (1)      NULL,
    CONSTRAINT [PK_Permessi2Funzione] PRIMARY KEY CLUSTERED ([COD_PERMESSO] ASC, [COD_FUNZIONE] ASC)
);


GO
PRINT N'Creating [dbo].[TabDifett]...';


GO
CREATE TABLE [dbo].[TabDifett] (
    [KeyAMI]     NVARCHAR (152)  NOT NULL,
    [ProcessNum] NVARCHAR (50)   NOT NULL,
    [CodItem]    NVARCHAR (50)   NOT NULL,
    [RawMat]     NVARCHAR (50)   NOT NULL,
    [CodPlant]   NVARCHAR (50)   NOT NULL,
    [TotOut]     DECIMAL (18, 6) NULL,
    [TotIn]      INT             NULL,
    CONSTRAINT [PK_TabDifett] PRIMARY KEY CLUSTERED ([KeyAMI] ASC, [ProcessNum] ASC)
);


GO
PRINT N'Creating [dbo].[DiesDet]...';


GO
CREATE TABLE [dbo].[DiesDet] (
    [CodDies]      NVARCHAR (50)  NOT NULL,
    [HoleNum]      INT            NOT NULL,
    [CodItem]      NVARCHAR (50)  NOT NULL,
    [CodDiesGroup] NVARCHAR (50)  NOT NULL,
    [Price]        DECIMAL (9, 3) NOT NULL,
    [TestCost]     DECIMAL (9, 3) NOT NULL,
    [ExpLife]      DECIMAL (9, 2) NOT NULL,
    [ActLife]      DECIMAL (9, 2) NOT NULL,
    [Active]       INT            NOT NULL,
    CONSTRAINT [PK_DiesDet] PRIMARY KEY CLUSTERED ([CodDies] ASC)
);


GO
PRINT N'Creating [dbo].[DiesDet].[i_DiesDet_CodItem_CodDiesGroup_Active]...';


GO
CREATE NONCLUSTERED INDEX [i_DiesDet_CodItem_CodDiesGroup_Active]
    ON [dbo].[DiesDet]([CodItem] ASC, [CodDiesGroup] ASC, [Active] ASC)
    INCLUDE([Price], [ExpLife], [ActLife]);


GO
PRINT N'Creating [dbo].[DiesDet].[i_DiesDet_Active_CodDiesGroup_Filtered]...';


GO
CREATE NONCLUSTERED INDEX [i_DiesDet_Active_CodDiesGroup_Filtered]
    ON [dbo].[DiesDet]([CodDiesGroup] ASC, [CodItem] ASC)
    INCLUDE([ActLife], [Price], [ExpLife]) WHERE ([Active]=(0));


GO
PRINT N'Creating [dbo].[ProductionLog]...';


GO
CREATE TABLE [dbo].[ProductionLog] (
    [EventStart]  DATETIME        NOT NULL,
    [EventEnd]    DATETIME        NOT NULL,
    [CodPlant]    NVARCHAR (50)   NOT NULL,
    [ProcessNum]  NVARCHAR (50)   NOT NULL,
    [NrPos]       NVARCHAR (50)   NOT NULL,
    [CodDies]     NVARCHAR (50)   NOT NULL,
    [CodClient]   NVARCHAR (50)   NOT NULL,
    [OrderNum]    NVARCHAR (50)   NOT NULL,
    [BatchNum]    NVARCHAR (50)   NOT NULL,
    [ProcessType] NVARCHAR (50)   NOT NULL,
    [EventType]   NVARCHAR (50)   NOT NULL,
    [RawMat]      NVARCHAR (50)   NOT NULL,
    [CodPackag]   NVARCHAR (50)   NOT NULL,
    [QtyIN]       DECIMAL (18, 4) NOT NULL,
    [QtyOUT]      DECIMAL (18, 4) NOT NULL,
    [QtyEXT]      DECIMAL (18, 4) NOT NULL,
    [NumIN]       INT             NOT NULL,
    [NumOUT]      INT             NOT NULL,
    [QuotaPlant]  DECIMAL (9, 4)  NOT NULL,
    [QuotaMan]    DECIMAL (9, 4)  NOT NULL,
    [Tags]        NVARCHAR (250)  NOT NULL,
    [Duration]    AS              (CONVERT (DECIMAL (12, 6), datediff(second, [EventStart], [EventEnd]) / (3600.00), (0))) PERSISTED,
    [okPr]        BIT             NOT NULL,
    [okQM]        BIT             NOT NULL,
    [okSc]        BIT             NOT NULL,
    [okDi]        BIT             NOT NULL,
    CONSTRAINT [PK_ProductionLog_1] PRIMARY KEY CLUSTERED ([EventStart] ASC, [EventEnd] ASC, [CodPlant] ASC, [ProcessNum] ASC, [NrPos] ASC, [CodDies] ASC)
);


GO
PRINT N'Creating [dbo].[ProductionLog].[i_ProductionLog_CodDies]...';


GO
CREATE NONCLUSTERED INDEX [i_ProductionLog_CodDies]
    ON [dbo].[ProductionLog]([CodDies] ASC)
    INCLUDE([EventStart], [RawMat]);


GO
PRINT N'Creating [dbo].[QuoteFull_Q]...';


GO
CREATE TABLE [dbo].[QuoteFull_Q] (
    [Vers]            VARCHAR (5)     NOT NULL,
    [QuoteType]       CHAR (1)        NOT NULL,
    [CodQuote]        BIGINT          NOT NULL,
    [QuoteRev]        INT             NOT NULL,
    [IdxQState]       INT             NOT NULL,
    [CodClient]       NVARCHAR (50)   NOT NULL,
    [ClientName]      NVARCHAR (250)  NOT NULL,
    [CodItem]         NVARCHAR (50)   NOT NULL,
    [CodItemGroup]    NVARCHAR (50)   NOT NULL,
    [RawMat]          NVARCHAR (50)   NOT NULL,
    [UnitWeight]      DECIMAL (9, 3)  NOT NULL,
    [BatchQty]        INT             NOT NULL,
    [CodInco]         NVARCHAR (5)    NOT NULL,
    [TranspZone]      NVARCHAR (50)   NOT NULL,
    [KeyAM]           NVARCHAR (101)  NOT NULL,
    [Note]            NVARCHAR (2500) NOT NULL,
    [PriceOff]        DECIMAL (9, 6)  NOT NULL,
    [CodClientAssoc]  NVARCHAR (100)  NULL,
    [ClientNameAssoc] NVARCHAR (100)  NULL,
    [ItemDescr]       NVARCHAR (100)  NULL,
    [CodifProfilo]    NVARCHAR (100)  NULL,
    [ClasseMerc]      NVARCHAR (100)  NULL,
    [TipoDies]        NVARCHAR (100)  NULL,
    [CodDiesGroup]    NVARCHAR (100)  NULL,
    [DiamDies]        DECIMAL (18, 6) NOT NULL,
    [HoleNumDies]     INT             NULL,
    [DiesPrice]       DECIMAL (18, 6) NOT NULL,
    [DiesExpLife]     DECIMAL (18, 6) NOT NULL,
    [DiesEOLife]      DECIMAL (18, 6) NOT NULL,
    [DiesByClass]     BIT             NOT NULL,
    [NumDiesInList]   DECIMAL (18, 6) NULL,
    [NumDiesExaust]   DECIMAL (18, 6) NULL,
    [CodPlant]        NVARCHAR (100)  NULL,
    [KeyAMIL]         NVARCHAR (100)  NULL,
    [KgTeo]           DECIMAL (18, 6) NULL,
    [NumSMED]         DECIMAL (18, 6) NULL,
    [QuotaMan]        DECIMAL (18, 6) NULL,
    [PRMWeight]       DECIMAL (18, 6) NULL,
    [PWeight]         DECIMAL (18, 6) NULL,
    [PTare]           DECIMAL (18, 6) NULL,
    [LivPackage]      NVARCHAR (100)  NULL,
    [LivPackageDett]  NVARCHAR (100)  NULL,
    [RawMatCost]      DECIMAL (18, 6) NOT NULL,
    [RawMatExtraCost] DECIMAL (18, 6) NOT NULL,
    [RawMatFullCost]  DECIMAL (18, 6) NULL,
    [CodPackag]       NVARCHAR (50)   NOT NULL,
    [PkgDesc]         NVARCHAR (100)  NULL,
    [FSR]             DECIMAL (18, 6) NULL,
    [ProvvCost]       DECIMAL (18, 6) NOT NULL,
    [EECost]          DECIMAL (18, 6) NOT NULL,
    [GasCost]         DECIMAL (18, 6) NOT NULL,
    [DiesCost]        DECIMAL (18, 6) NOT NULL,
    [PackCost]        DECIMAL (18, 6) NOT NULL,
    [TranspCost]      DECIMAL (18, 6) NOT NULL,
    [SellCost01]      DECIMAL (18, 6) NOT NULL,
    [RefCost01]       DECIMAL (18, 6) NOT NULL,
    [SellCost04]      DECIMAL (18, 6) NOT NULL,
    [RefCost04]       DECIMAL (18, 6) NOT NULL,
    [WSR01]           DECIMAL (9, 8)  NOT NULL,
    [MSR01]           DECIMAL (9, 8)  NOT NULL,
    [NetProd01]       DECIMAL (9, 3)  NOT NULL,
    [FC4UG01]         DECIMAL (9, 6)  NOT NULL,
    [VC4UG01]         DECIMAL (9, 6)  NOT NULL,
    [OH4UG01]         DECIMAL (9, 6)  NOT NULL,
    [SC4UG01]         DECIMAL (9, 6)  NOT NULL,
    [DSR]             DECIMAL (9, 8)  NULL,
    [NetProd04]       DECIMAL (9, 3)  NOT NULL,
    [FC4UG04]         DECIMAL (9, 6)  NOT NULL,
    [VC4UG04]         DECIMAL (9, 6)  NOT NULL,
    [FVC]             DECIMAL (18, 6) NULL,
    [Charge]          DECIMAL (9, 6)  NOT NULL,
    [valid]           BIT             NOT NULL,
    [errorScore]      INT             NOT NULL,
    CONSTRAINT [PK_QuoteFull_Q_1] PRIMARY KEY CLUSTERED ([QuoteType] ASC, [CodQuote] ASC, [QuoteRev] ASC)
);


GO
PRINT N'Creating [dbo].[QuoteList]...';


GO
CREATE TABLE [dbo].[QuoteList] (
    [QuoteType]    CHAR (1)        NOT NULL,
    [CodQuote]     BIGINT          NOT NULL,
    [QuoteRev]     INT             NOT NULL,
    [IdxQState]    INT             NOT NULL,
    [CodClient]    NVARCHAR (50)   NOT NULL,
    [CodItem]      NVARCHAR (50)   NOT NULL,
    [CodItemGroup] NVARCHAR (50)   NOT NULL,
    [RawMat]       NVARCHAR (50)   NOT NULL,
    [UnitWeight]   DECIMAL (9, 3)  NOT NULL,
    [BatchQty]     INT             NOT NULL,
    [CodInco]      NVARCHAR (5)    NOT NULL,
    [KeyAM]        AS              ((CASE WHEN [QuoteType] = 'S' THEN [CodItemGroup] ELSE [CodItem] END + '-') + [RawMat]),
    [Note]         NVARCHAR (2500) NOT NULL,
    [PriceOff]     DECIMAL (9, 6)  NOT NULL,
    [OrdDate]      SMALLDATETIME   NULL,
    [OrdNum]       NVARCHAR (50)   NOT NULL,
    [OrdRow]       NVARCHAR (50)   NOT NULL,
    [OrdPrice]     DECIMAL (9, 6)  NOT NULL,
    [OrdQty]       INT             NOT NULL,
    [valid]        BIT             NOT NULL,
    [errorScore]   INT             NOT NULL,
    [UserCreaz]    NVARCHAR (50)   NOT NULL,
    [DataCreaz]    DATETIME        NOT NULL,
    [UserMod]      NVARCHAR (50)   NOT NULL,
    [DataMod]      DATETIME        NOT NULL,
    CONSTRAINT [PK_QuoteList_1] PRIMARY KEY CLUSTERED ([QuoteType] ASC, [CodQuote] ASC, [QuoteRev] ASC) WITH (FILLFACTOR = 90)
);


GO
PRINT N'Creating [dbo].[QuoteParam]...';


GO
CREATE TABLE [dbo].[QuoteParam] (
    [QuoteType]  CHAR (1)       NOT NULL,
    [CodQuote]   BIGINT         NOT NULL,
    [QuoteRev]   INT            NOT NULL,
    [NumP]       INT            NOT NULL,
    [ProcessNum] NVARCHAR (50)  NOT NULL,
    [Descr]      NVARCHAR (50)  NOT NULL,
    [Parameter]  NVARCHAR (100) NOT NULL,
    CONSTRAINT [PK_QuoteParam] PRIMARY KEY CLUSTERED ([QuoteType] ASC, [CodQuote] ASC, [QuoteRev] ASC, [NumP] ASC) WITH (FILLFACTOR = 90)
);


GO
PRINT N'Creating [dbo].[QuoteWorkInt]...';


GO
CREATE TABLE [dbo].[QuoteWorkInt] (
    [QuoteType]  CHAR (1)       NOT NULL,
    [CodQuote]   BIGINT         NOT NULL,
    [QuoteRev]   INT            NOT NULL,
    [NumWI]      INT            NOT NULL,
    [ProcessNum] NVARCHAR (50)  NOT NULL,
    [CodPlant]   NVARCHAR (50)  NOT NULL,
    [Class01]    NVARCHAR (50)  NOT NULL,
    [Class02]    NVARCHAR (50)  NOT NULL,
    [Class03]    NVARCHAR (50)  NOT NULL,
    [Class04]    NVARCHAR (50)  NOT NULL,
    [Class05]    NVARCHAR (50)  NOT NULL,
    [NetProd]    DECIMAL (9, 3) NOT NULL,
    [WSR]        DECIMAL (9, 8) NOT NULL,
    [MSR]        DECIMAL (9, 8) NOT NULL,
    [DSR]        DECIMAL (9, 8) NOT NULL,
    [FC4UG]      DECIMAL (9, 6) NOT NULL,
    [VC4UG]      DECIMAL (9, 6) NOT NULL,
    [OH4UG]      DECIMAL (9, 6) NOT NULL,
    [SC4UG]      DECIMAL (9, 6) NOT NULL,
    [WYR]        AS             ((1) - [WSR]),
    [MYR]        AS             ((1) - [MSR]),
    [DYR]        AS             ((1) - [DSR]),
    [WCR]        AS             (CASE WHEN ((1) - [WSR]) = (0) THEN (1) ELSE (1) / ((1) - [WSR]) END),
    [MCR]        AS             (CASE WHEN ((1) - [MSR]) = (0) THEN (1) ELSE (1) / ((1) - [MSR]) END),
    [DCR]        AS             (CASE WHEN ((1) - [DSR]) = (0) THEN (1) ELSE (1) / ((1) - [DSR]) END),
    [valid]      BIT            NOT NULL,
    CONSTRAINT [PK_QuoteWorkInt] PRIMARY KEY CLUSTERED ([QuoteType] ASC, [CodQuote] ASC, [QuoteRev] ASC, [NumWI] ASC) WITH (FILLFACTOR = 90)
);


GO
PRINT N'Creating [dbo].[RawMatDet]...';


GO
CREATE TABLE [dbo].[RawMatDet] (
    [RawMat]        NVARCHAR (50)   NOT NULL,
    [ProcCost]      DECIMAL (18, 6) NOT NULL,
    [ProcYield]     DECIMAL (9, 6)  NOT NULL,
    [CSR]           DECIMAL (9, 6)  NOT NULL,
    [SSR]           DECIMAL (9, 6)  NULL,
    [SSVA]          DECIMAL (9, 6)  NULL,
    [SSVR]          DECIMAL (9, 6)  NULL,
    [ExtraMatCost]  DECIMAL (9, 6)  NULL,
    [ExtraServCost] DECIMAL (9, 6)  NULL,
    CONSTRAINT [PK_RawMatDet] PRIMARY KEY CLUSTERED ([RawMat] ASC)
);


GO
PRINT N'Creating [dbo].[TabProdSc]...';


GO
CREATE TABLE [dbo].[TabProdSc] (
    [KeyAMIL]      NVARCHAR (250)  NOT NULL,
    [CodDiesGroup] NVARCHAR (50)   NOT NULL,
    [KeyAM]        NVARCHAR (250)  NOT NULL,
    [CodItem]      NVARCHAR (50)   NOT NULL,
    [RawMat]       NVARCHAR (50)   NOT NULL,
    [CodPlant]     NVARCHAR (50)   NOT NULL,
    [HoleNum]      INT             NOT NULL,
    [NumSMED]      INT             NOT NULL,
    [KgTeo]        DECIMAL (18, 6) NOT NULL,
    [KgLor]        DECIMAL (18, 6) NOT NULL,
    [Duration]     DECIMAL (18, 6) NOT NULL,
    [ProdTeo]      AS              (CASE isnull([Duration], (0)) WHEN (0) THEN (0) ELSE isnull([KgTeo], (0)) / [Duration] END),
    [ScTec]        AS              (CASE isnull([KgLor], (0)) WHEN (0) THEN (0) ELSE (1) - [KgTeo] / [KgLor] END),
    CONSTRAINT [PK_TabProdSc] PRIMARY KEY CLUSTERED ([KeyAMIL] ASC, [CodDiesGroup] ASC)
);


GO
PRINT N'Creating [dbo].[TabProdSc].[i_TabProdSc_KeyAM]...';


GO
CREATE NONCLUSTERED INDEX [i_TabProdSc_KeyAM]
    ON [dbo].[TabProdSc]([KeyAM] ASC)
    INCLUDE([KgTeo]);


GO
PRINT N'Creating [dbo].[TrascDies]...';


GO
CREATE TABLE [dbo].[TrascDies] (
    [CodDies]    NVARCHAR (50) NOT NULL,
    [CodDiesNew] NVARCHAR (50) NOT NULL
);


GO
PRINT N'Creating [dbo].[TrascItem]...';


GO
CREATE TABLE [dbo].[TrascItem] (
    [CodItem]     NVARCHAR (50)  NOT NULL,
    [ItemDescr]   NVARCHAR (250) NOT NULL,
    [CodItemNew]  NVARCHAR (50)  NOT NULL,
    [ItemDescNew] NVARCHAR (250) NOT NULL
);


GO
PRINT N'Creating [dbo].[TrascPlan]...';


GO
CREATE TABLE [dbo].[TrascPlan] (
    [CodPlant]    NVARCHAR (50) NOT NULL,
    [CodPlantNew] NVARCHAR (50) NOT NULL
);


GO
PRINT N'Creating [dbo].[UTENTE]...';


GO
CREATE TABLE [dbo].[UTENTE] (
    [DOMINIO]     VARCHAR (30)  NULL,
    [USER_NAME]   NVARCHAR (50) NOT NULL,
    [COGNOME]     VARCHAR (100) NULL,
    [NOME]        VARCHAR (100) NULL,
    [COD_SOCIETA] VARCHAR (5)   NULL,
    [MATRICOLA]   VARCHAR (5)   NULL,
    [COD_CDC]     VARCHAR (10)  NULL,
    [EMAIL]       VARCHAR (100) NULL,
    [SIGLA]       NVARCHAR (5)  NULL,
    [COD_LINGUA]  VARCHAR (3)   NULL,
    [ATTIVO]      CHAR (1)      NULL,
    CONSTRAINT [PK_UTENTE] PRIMARY KEY CLUSTERED ([USER_NAME] ASC)
);


GO
PRINT N'Creating [dbo].[OrdersHist]...';


GO
CREATE TABLE [dbo].[OrdersHist] (
    [OrdNum]          NVARCHAR (50)   NOT NULL,
    [OrdRow]          NVARCHAR (50)   NOT NULL,
    [OrdDate]         SMALLDATETIME   NOT NULL,
    [CodClient]       NVARCHAR (50)   NOT NULL,
    [CodItem]         NVARCHAR (50)   NOT NULL,
    [RawMat]          NVARCHAR (50)   NOT NULL,
    [RawMatCost]      DECIMAL (18, 6) NOT NULL,
    [BatchQty]        INT             NOT NULL,
    [CodInco]         NVARCHAR (5)    NOT NULL,
    [OrdPrice]        DECIMAL (9, 6)  NOT NULL,
    [RawMatExtraCost] DECIMAL (18, 6) NOT NULL,
    [PriceOff]        DECIMAL (9, 6)  NOT NULL,
    [OrdQty]          INT             NOT NULL,
    [QuoteType]       CHAR (1)        NOT NULL,
    [CodQuote]        BIGINT          NOT NULL,
    [QuoteRev]        INT             NOT NULL,
    [ProvvCost]       DECIMAL (9, 6)  NOT NULL,
    [EndCalc]         DATETIME        NULL,
    CONSTRAINT [PK_OrdersHist] PRIMARY KEY CLUSTERED ([OrdNum] ASC, [OrdRow] ASC) WITH (FILLFACTOR = 100)
);


GO
PRINT N'Creating [dbo].[OrdersHist].[idx_OH_quote]...';


GO
CREATE NONCLUSTERED INDEX [idx_OH_quote]
    ON [dbo].[OrdersHist]([CodQuote] ASC, [QuoteRev] ASC) WITH (FILLFACTOR = 100);


GO
PRINT N'Creating [dbo].[PickList]...';


GO
CREATE TABLE [dbo].[PickList] (
    [CodList] NVARCHAR (50) NOT NULL,
    [Value]   NVARCHAR (50) NOT NULL,
    [Lemma]   NVARCHAR (50) NOT NULL,
    [NumOrd]  INT           NOT NULL,
    CONSTRAINT [PK_PickList] PRIMARY KEY CLUSTERED ([CodList] ASC, [Value] ASC)
);


GO
PRINT N'Creating [dbo].[QuoteFull_C]...';


GO
CREATE TABLE [dbo].[QuoteFull_C] (
    [Vers]           VARCHAR (5)     NOT NULL,
    [QuoteType]      CHAR (1)        NOT NULL,
    [CodQuote]       BIGINT          NOT NULL,
    [QuoteRev]       INT             NOT NULL,
    [Class01]        NVARCHAR (50)   NOT NULL,
    [Class02]        NVARCHAR (50)   NOT NULL,
    [CodItem]        NVARCHAR (50)   NOT NULL,
    [RawMat]         NVARCHAR (50)   NOT NULL,
    [CodPlant]       NVARCHAR (50)   NOT NULL,
    [CodDiesGroup]   NVARCHAR (50)   NOT NULL,
    [CodPackag]      NVARCHAR (50)   NOT NULL,
    [batchQty]       INT             NOT NULL,
    [CodInco]        NVARCHAR (5)    NOT NULL,
    [RawMatFullCost] NUMERIC (18, 6) NOT NULL,
    [FVC]            DECIMAL (18, 6) NOT NULL,
    [FullCost]       DECIMAL (18, 6) NOT NULL,
    [valid]          BIT             NULL,
    [errorScore]     INT             NULL,
    CONSTRAINT [PK_QuoteFull_C] PRIMARY KEY CLUSTERED ([QuoteType] ASC, [CodQuote] ASC, [QuoteRev] ASC)
);


GO
PRINT N'Creating [dbo].[QuoteFull_R]...';


GO
CREATE TABLE [dbo].[QuoteFull_R] (
    [Vers]            VARCHAR (5)     NOT NULL,
    [QuoteType]       CHAR (1)        NOT NULL,
    [CodQuote]        BIGINT          NOT NULL,
    [QuoteRev]        INT             NOT NULL,
    [IdxQState]       INT             NOT NULL,
    [CodClient]       NVARCHAR (50)   NOT NULL,
    [ClientName]      NVARCHAR (250)  NOT NULL,
    [CodItem]         NVARCHAR (50)   NOT NULL,
    [CodItemGroup]    NVARCHAR (50)   NOT NULL,
    [RawMat]          NVARCHAR (50)   NOT NULL,
    [UnitWeight]      DECIMAL (9, 3)  NOT NULL,
    [BatchQty]        INT             NOT NULL,
    [CodInco]         NVARCHAR (5)    NOT NULL,
    [TranspZone]      NVARCHAR (50)   NOT NULL,
    [KeyAM]           NVARCHAR (101)  NOT NULL,
    [Note]            NVARCHAR (2500) NOT NULL,
    [PriceOff]        DECIMAL (9, 6)  NOT NULL,
    [CodClientAssoc]  NVARCHAR (100)  NULL,
    [ClientNameAssoc] NVARCHAR (100)  NULL,
    [ItemDescr]       NVARCHAR (100)  NULL,
    [CodifProfilo]    NVARCHAR (100)  NULL,
    [ClasseMerc]      NVARCHAR (100)  NULL,
    [TipoDies]        NVARCHAR (100)  NULL,
    [CodDiesGroup]    NVARCHAR (100)  NULL,
    [DiamDies]        DECIMAL (18, 6) NOT NULL,
    [HoleNumDies]     INT             NULL,
    [DiesPrice]       DECIMAL (18, 6) NOT NULL,
    [DiesExpLife]     DECIMAL (18, 6) NOT NULL,
    [DiesEOLife]      DECIMAL (18, 6) NOT NULL,
    [DiesByClass]     BIT             NOT NULL,
    [NumDiesInList]   DECIMAL (18, 6) NULL,
    [NumDiesExaust]   DECIMAL (18, 6) NULL,
    [CodPlant]        NVARCHAR (100)  NULL,
    [KeyAMIL]         NVARCHAR (100)  NULL,
    [KgTeo]           DECIMAL (18, 6) NULL,
    [NumSMED]         INT             NULL,
    [QuotaMan]        DECIMAL (18, 6) NULL,
    [PRMWeight]       DECIMAL (18, 6) NULL,
    [PWeight]         DECIMAL (18, 6) NULL,
    [PTare]           DECIMAL (18, 6) NULL,
    [LivPackage]      NVARCHAR (100)  NULL,
    [LivPackageDett]  NVARCHAR (100)  NULL,
    [RawMatCost]      DECIMAL (18, 6) NOT NULL,
    [RawMatExtraCost] DECIMAL (18, 6) NOT NULL,
    [RawMatFullCost]  DECIMAL (18, 6) NULL,
    [CodPackag]       NVARCHAR (50)   NOT NULL,
    [PkgDesc]         NVARCHAR (100)  NULL,
    [FSR]             DECIMAL (18, 6) NULL,
    [ProvvCost]       DECIMAL (18, 6) NOT NULL,
    [EECost]          DECIMAL (18, 6) NOT NULL,
    [GasCost]         DECIMAL (18, 6) NOT NULL,
    [DiesCost]        DECIMAL (18, 6) NOT NULL,
    [PackCost]        DECIMAL (18, 6) NOT NULL,
    [TranspCost]      DECIMAL (18, 6) NOT NULL,
    [SellCost01]      DECIMAL (18, 6) NOT NULL,
    [RefCost01]       DECIMAL (18, 6) NOT NULL,
    [SellCost04]      DECIMAL (18, 6) NOT NULL,
    [RefCost04]       DECIMAL (18, 6) NOT NULL,
    [WSR01]           DECIMAL (9, 8)  NOT NULL,
    [MSR01]           DECIMAL (9, 8)  NOT NULL,
    [NetProd01]       DECIMAL (9, 3)  NOT NULL,
    [FC4UG01]         DECIMAL (9, 6)  NOT NULL,
    [VC4UG01]         DECIMAL (9, 6)  NOT NULL,
    [OH4UG01]         DECIMAL (9, 6)  NOT NULL,
    [SC4UG01]         DECIMAL (9, 6)  NOT NULL,
    [DSR]             DECIMAL (9, 8)  NULL,
    [NetProd04]       DECIMAL (9, 3)  NOT NULL,
    [FC4UG04]         DECIMAL (9, 6)  NOT NULL,
    [VC4UG04]         DECIMAL (9, 6)  NOT NULL,
    [FVC]             DECIMAL (18, 6) NULL,
    [Charge]          DECIMAL (9, 6)  NOT NULL,
    [OrdDate]         SMALLDATETIME   NOT NULL,
    [OrdNum]          NVARCHAR (50)   NOT NULL,
    [OrdRow]          NVARCHAR (50)   NOT NULL,
    [OrdPrice]        DECIMAL (9, 6)  NOT NULL,
    [OrdQty]          INT             NOT NULL,
    [valid]           BIT             NOT NULL,
    [errorScore]      INT             NOT NULL,
    CONSTRAINT [PK_QuoteFull_R_1] PRIMARY KEY CLUSTERED ([QuoteType] ASC, [CodQuote] ASC, [QuoteRev] ASC) WITH (FILLFACTOR = 90)
);


GO
PRINT N'Creating [dbo].[QuoteSimPar]...';


GO
CREATE TABLE [dbo].[QuoteSimPar] (
    [QuoteType] CHAR (1)      NOT NULL,
    [CodQuote]  BIGINT        NOT NULL,
    [QuoteRev]  INT           NOT NULL,
    [NomePar]   NVARCHAR (50) NOT NULL,
    [ValPar]    NVARCHAR (50) NOT NULL,
    CONSTRAINT [PK_QuoteSimPar_1] PRIMARY KEY CLUSTERED ([QuoteType] ASC, [CodQuote] ASC, [QuoteRev] ASC, [NomePar] ASC) WITH (FILLFACTOR = 90)
);


GO
PRINT N'Creating [dbo].[ReportPrintTicket]...';


GO
CREATE TABLE [dbo].[ReportPrintTicket] (
    [Ticket]    INT            NOT NULL,
    [Report]    NVARCHAR (50)  NOT NULL,
    [Chiave]    NVARCHAR (250) NOT NULL,
    [UserReq]   NVARCHAR (50)  NOT NULL,
    [DataReq]   DATETIME       NOT NULL,
    [DataPrint] DATETIME       NULL,
    CONSTRAINT [PK_ReportPrintTicket] PRIMARY KEY CLUSTERED ([Ticket] ASC, [Report] ASC, [Chiave] ASC)
);


GO
PRINT N'Creating [dbo].[TrascClass01]...';


GO
CREATE TABLE [dbo].[TrascClass01] (
    [Class01]    NVARCHAR (50) NOT NULL,
    [Class01New] NVARCHAR (50) NOT NULL
);


GO
PRINT N'Creating [dbo].[TrascClass02]...';


GO
CREATE TABLE [dbo].[TrascClass02] (
    [Class02]    NVARCHAR (50) NOT NULL,
    [Class02New] NVARCHAR (50) NOT NULL
);


GO
PRINT N'Creating [dbo].[TrascClass03]...';


GO
CREATE TABLE [dbo].[TrascClass03] (
    [Class03]    NVARCHAR (50) NOT NULL,
    [Class03New] NVARCHAR (50) NOT NULL
);


GO
PRINT N'Creating [dbo].[TrascClient]...';


GO
CREATE TABLE [dbo].[TrascClient] (
    [CodClient]     NVARCHAR (50)  NOT NULL,
    [ClientName]    NVARCHAR (250) NOT NULL,
    [CodClientNew]  NVARCHAR (50)  NOT NULL,
    [ClientNameNew] NVARCHAR (250) NOT NULL
);


GO
PRINT N'Creating [dbo].[CDC]...';


GO
CREATE TABLE [dbo].[CDC] (
    [COD_CDC]     VARCHAR (10)  NOT NULL,
    [DESCRIZIONE] VARCHAR (200) NULL,
    [COD_TIPO]    VARCHAR (1)   NOT NULL,
    [POSIZIONE]   VARCHAR (100) NULL,
    PRIMARY KEY CLUSTERED ([COD_CDC] ASC)
);


GO
PRINT N'Creating [dbo].[ContatoriQuote]...';


GO
CREATE TABLE [dbo].[ContatoriQuote] (
    [Flusso]  VARCHAR (2) NOT NULL,
    [LastIdx] INT         NOT NULL,
    CONSTRAINT [PK_ContatoriQuote] PRIMARY KEY CLUSTERED ([Flusso] ASC)
);


GO
PRINT N'Creating [dbo].[CostList]...';


GO
CREATE TABLE [dbo].[CostList] (
    [DateList]        SMALLDATETIME   NOT NULL,
    [CodItem]         NVARCHAR (50)   NOT NULL,
    [RawMat]          NVARCHAR (50)   NOT NULL,
    [RawMatCost]      DECIMAL (18, 6) NOT NULL,
    [RawMatExtraCost] DECIMAL (18, 6) NULL,
    [batchQty]        INT             NOT NULL,
    [CodInco]         NVARCHAR (5)    NOT NULL,
    [QuoteType]       CHAR (1)        NOT NULL,
    [CodQuote]        BIGINT          NOT NULL,
    [QuoteRev]        INT             NOT NULL,
    [EndCalc]         DATETIME        NULL,
    CONSTRAINT [PK_CostList_1] PRIMARY KEY CLUSTERED ([DateList] ASC, [CodItem] ASC, [RawMat] ASC)
);


GO
PRINT N'Creating [dbo].[CostList].[ix_CostList_QuoteType_CodQuote]...';


GO
CREATE NONCLUSTERED INDEX [ix_CostList_QuoteType_CodQuote]
    ON [dbo].[CostList]([QuoteType] ASC, [CodQuote] ASC);


GO
PRINT N'Creating [dbo].[DIRITTI]...';


GO
CREATE TABLE [dbo].[DIRITTI] (
    [USER_NAME]    NVARCHAR (50) NOT NULL,
    [COD_CDC]      NVARCHAR (50) NOT NULL,
    [COD_MODULO]   NVARCHAR (31) NOT NULL,
    [COD_FUNZIONE] NVARCHAR (31) NOT NULL,
    [VALUE]        VARCHAR (255) NULL,
    CONSTRAINT [PK_DIRITTI] PRIMARY KEY CLUSTERED ([USER_NAME] ASC, [COD_CDC] ASC, [COD_MODULO] ASC, [COD_FUNZIONE] ASC)
);


GO
PRINT N'Creating [dbo].[FUNZIONE]...';


GO
CREATE TABLE [dbo].[FUNZIONE] (
    [COD_FUNZIONE] NVARCHAR (31)  NOT NULL,
    [DESCRIZIONE]  NVARCHAR (500) NULL,
    CONSTRAINT [PK_FUNZIONE] PRIMARY KEY CLUSTERED ([COD_FUNZIONE] ASC)
);


GO
PRINT N'Creating [dbo].[MODULO]...';


GO
CREATE TABLE [dbo].[MODULO] (
    [COD_MODULO]  NVARCHAR (31) NOT NULL,
    [DESCRIZIONE] VARCHAR (200) NULL,
    CONSTRAINT [PK_MODULO] PRIMARY KEY CLUSTERED ([COD_MODULO] ASC)
);


GO
PRINT N'Creating [dbo].[QuoteFull_S]...';


GO
CREATE TABLE [dbo].[QuoteFull_S] (
    [Vers]                 VARCHAR (5)     NOT NULL,
    [QuoteType]            CHAR (1)        NOT NULL,
    [CodQuote]             BIGINT          NOT NULL,
    [QuoteRev]             INT             NOT NULL,
    [IdxQState]            INT             NOT NULL,
    [CodClient]            NVARCHAR (50)   NOT NULL,
    [ClientName]           NVARCHAR (250)  NOT NULL,
    [CodItem]              NVARCHAR (50)   NOT NULL,
    [CodItemGroup]         NVARCHAR (50)   NOT NULL,
    [RawMat]               NVARCHAR (50)   NOT NULL,
    [UnitWeight]           DECIMAL (9, 3)  NOT NULL,
    [BatchQty]             INT             NOT NULL,
    [CodInco]              NVARCHAR (5)    NOT NULL,
    [TranspZone]           NVARCHAR (50)   NOT NULL,
    [KeyAM]                NVARCHAR (101)  NOT NULL,
    [Note]                 NVARCHAR (2500) NOT NULL,
    [PriceOff]             DECIMAL (9, 6)  NOT NULL,
    [CodClientAssoc]       NVARCHAR (100)  NULL,
    [ClientNameAssoc]      NVARCHAR (100)  NULL,
    [ItemDescr]            NVARCHAR (100)  NULL,
    [CodifProfilo]         NVARCHAR (100)  NULL,
    [ClasseMerc]           NVARCHAR (100)  NULL,
    [TipoDies]             NVARCHAR (100)  NULL,
    [CodDiesGroup]         NVARCHAR (100)  NULL,
    [DiamDies]             DECIMAL (18, 6) NOT NULL,
    [HoleNumDies]          INT             NOT NULL,
    [DiesPrice_sim]        DECIMAL (18, 6) NOT NULL,
    [DiesPrice]            DECIMAL (18, 6) NOT NULL,
    [SamplePrice]          DECIMAL (18, 6) NOT NULL,
    [DiesFullCost]         DECIMAL (18, 6) NOT NULL,
    [DiesPriceClientQuote] DECIMAL (18, 6) NOT NULL,
    [DiesExpLife]          DECIMAL (18, 6) NOT NULL,
    [DiesEOLife]           DECIMAL (18, 6) NOT NULL,
    [DiesTecLife]          DECIMAL (18, 6) NOT NULL,
    [DiesCommLife]         DECIMAL (18, 6) NOT NULL,
    [MonthSalesPrev]       INT             NOT NULL,
    [SalesPrevCost]        DECIMAL (18, 6) NOT NULL,
    [DiesFinCost]          DECIMAL (18, 6) NOT NULL,
    [ClientQuoteReven]     DECIMAL (18, 6) NOT NULL,
    [ExtraDiscountDies]    DECIMAL (18, 6) NOT NULL,
    [DiesByClass]          BIT             NOT NULL,
    [NumDiesInList]        DECIMAL (18, 6) NOT NULL,
    [NumDiesExaust]        DECIMAL (18, 6) NOT NULL,
    [CodPlant]             NVARCHAR (100)  NULL,
    [KeyAMIL]              NVARCHAR (100)  NULL,
    [KgTeo]                DECIMAL (18, 6) NOT NULL,
    [NumSMED]              INT             NOT NULL,
    [QuotaMan]             DECIMAL (18, 6) NOT NULL,
    [PRMWeight]            DECIMAL (18, 6) NOT NULL,
    [PWeight]              DECIMAL (18, 6) NOT NULL,
    [PTare]                DECIMAL (18, 6) NOT NULL,
    [LivPackage]           NVARCHAR (100)  NULL,
    [LivPackageDett]       NVARCHAR (100)  NULL,
    [RawMatCost]           DECIMAL (18, 6) NOT NULL,
    [RawMatExtraCost]      DECIMAL (18, 6) NOT NULL,
    [RawMatFullCost]       DECIMAL (18, 6) NOT NULL,
    [CodPackag]            NVARCHAR (50)   NOT NULL,
    [PkgDesc]              NVARCHAR (100)  NULL,
    [FSR]                  DECIMAL (18, 6) NOT NULL,
    [ProvvCost]            DECIMAL (18, 6) NOT NULL,
    [EECost]               DECIMAL (18, 6) NOT NULL,
    [GasCost]              DECIMAL (18, 6) NOT NULL,
    [DiesCost]             DECIMAL (18, 6) NOT NULL,
    [PackCost]             DECIMAL (18, 6) NOT NULL,
    [TranspCost]           DECIMAL (18, 6) NOT NULL,
    [SellCost01]           DECIMAL (18, 6) NOT NULL,
    [RefCost01]            DECIMAL (18, 6) NOT NULL,
    [SellCost04]           DECIMAL (18, 6) NOT NULL,
    [RefCost04]            DECIMAL (18, 6) NOT NULL,
    [WSR01_sim]            DECIMAL (9, 8)  NOT NULL,
    [WSR01]                DECIMAL (9, 8)  NOT NULL,
    [MSR01_sim]            DECIMAL (9, 8)  NOT NULL,
    [MSR01]                DECIMAL (9, 8)  NOT NULL,
    [NetProd01_sim]        DECIMAL (9, 3)  NOT NULL,
    [NetProd04_sim]        DECIMAL (9, 3)  NOT NULL,
    [NetProd01]            DECIMAL (9, 3)  NOT NULL,
    [FC4UG01]              DECIMAL (9, 6)  NOT NULL,
    [VC4UG01]              DECIMAL (9, 6)  NOT NULL,
    [OH4UG01]              DECIMAL (9, 6)  NOT NULL,
    [SC4UG01]              DECIMAL (9, 6)  NOT NULL,
    [DSR_sim]              DECIMAL (9, 8)  NOT NULL,
    [DSR]                  DECIMAL (9, 8)  NOT NULL,
    [NetProd04]            DECIMAL (9, 3)  NOT NULL,
    [FC4UG04]              DECIMAL (9, 6)  NOT NULL,
    [VC4UG04]              DECIMAL (9, 6)  NOT NULL,
    [FVC]                  DECIMAL (18, 6) NOT NULL,
    [Charge]               DECIMAL (9, 6)  NOT NULL,
    [valid]                BIT             NOT NULL,
    [errorScore]           INT             NOT NULL,
    CONSTRAINT [PK_QuoteFull_S] PRIMARY KEY CLUSTERED ([QuoteType] ASC, [CodQuote] ASC, [QuoteRev] ASC)
);


GO
PRINT N'Creating [dbo].[ListValues]...';


GO
CREATE TABLE [dbo].[ListValues] (
    [TableName] NVARCHAR (50) NOT NULL,
    [FieldName] NVARCHAR (50) NOT NULL,
    [value]     NVARCHAR (10) NOT NULL,
    [label]     NVARCHAR (50) NULL,
    [ordinal]   INT           NULL,
    CONSTRAINT [PK_ListValues] PRIMARY KEY CLUSTERED ([TableName] ASC, [FieldName] ASC, [value] ASC)
);


GO
PRINT N'Creating [tmp].[ProductionLogRaw_old]...';


GO
CREATE TABLE [tmp].[ProductionLogRaw_old] (
    [EventStart]  NVARCHAR (50)  NOT NULL,
    [EventEnd]    NVARCHAR (50)  NOT NULL,
    [CodPlant]    NVARCHAR (50)  NOT NULL,
    [ProcessNum]  NVARCHAR (50)  NOT NULL,
    [NrPos]       NVARCHAR (50)  NOT NULL,
    [CodDies]     NVARCHAR (50)  NOT NULL,
    [CodClient]   NVARCHAR (50)  NOT NULL,
    [OrderNum]    NVARCHAR (50)  NOT NULL,
    [BatchNum]    NVARCHAR (50)  NOT NULL,
    [ProcessType] NVARCHAR (50)  NOT NULL,
    [EventType]   NVARCHAR (50)  NOT NULL,
    [RawMat]      NVARCHAR (50)  NOT NULL,
    [CodPackag]   NVARCHAR (50)  NOT NULL,
    [QtyIN]       NVARCHAR (50)  NOT NULL,
    [QtyOUT]      NVARCHAR (50)  NOT NULL,
    [QtyEXT]      NVARCHAR (50)  NOT NULL,
    [NumIN]       NVARCHAR (50)  NOT NULL,
    [NumOUT]      NVARCHAR (50)  NOT NULL,
    [QuotaPlant]  NVARCHAR (50)  NOT NULL,
    [QuotaMan]    NVARCHAR (50)  NOT NULL,
    [Tags]        NVARCHAR (250) NOT NULL
);


GO
PRINT N'Creating [tmp].[DiesRaw]...';


GO
CREATE TABLE [tmp].[DiesRaw] (
    [CodDies]      NVARCHAR (50) NOT NULL,
    [HoleNum]      NVARCHAR (50) NOT NULL,
    [CodItem]      NVARCHAR (50) NOT NULL,
    [CodDiesGroup] NVARCHAR (50) NOT NULL,
    [Price]        NVARCHAR (50) NOT NULL,
    [ExpLife]      NVARCHAR (50) NOT NULL,
    [ActLife]      NVARCHAR (50) NOT NULL,
    [Active]       NVARCHAR (50) NOT NULL
);


GO
PRINT N'Creating [tmp].[ProductionLogRaw_KO]...';


GO
CREATE TABLE [tmp].[ProductionLogRaw_KO] (
    [EventStart]  NVARCHAR (50)  NOT NULL,
    [EventEnd]    NVARCHAR (50)  NOT NULL,
    [CodPlant]    NVARCHAR (50)  NOT NULL,
    [ProcessNum]  NVARCHAR (50)  NOT NULL,
    [NrPos]       NVARCHAR (50)  NOT NULL,
    [CodDies]     NVARCHAR (50)  NOT NULL,
    [CodClient]   NVARCHAR (50)  NOT NULL,
    [OrderNum]    NVARCHAR (50)  NOT NULL,
    [BatchNum]    NVARCHAR (50)  NOT NULL,
    [ProcessType] NVARCHAR (50)  NOT NULL,
    [EventType]   NVARCHAR (50)  NOT NULL,
    [RawMat]      NVARCHAR (50)  NOT NULL,
    [CodPackag]   NVARCHAR (50)  NOT NULL,
    [QtyIN]       NVARCHAR (50)  NOT NULL,
    [QtyOUT]      NVARCHAR (50)  NOT NULL,
    [QtyEXT]      NVARCHAR (50)  NOT NULL,
    [NumIN]       NVARCHAR (50)  NOT NULL,
    [NumOUT]      NVARCHAR (50)  NOT NULL,
    [QuotaPlant]  NVARCHAR (50)  NOT NULL,
    [QuotaMan]    NVARCHAR (50)  NOT NULL,
    [Tags]        NVARCHAR (250) NOT NULL,
    [okPr]        BIT            NOT NULL,
    [okQM]        BIT            NOT NULL,
    [okSc]        BIT            NOT NULL,
    [okDi]        BIT            NOT NULL,
    [ImportDate]  DATETIME       NULL
);


GO
PRINT N'Creating [tmp].[ClientsRaw]...';


GO
CREATE TABLE [tmp].[ClientsRaw] (
    [CodClient]  NVARCHAR (50)  NOT NULL,
    [ClientName] NVARCHAR (250) NOT NULL,
    [CodAg]      NVARCHAR (50)  NOT NULL,
    [ZipCode]    NVARCHAR (50)  NOT NULL,
    [City]       NVARCHAR (50)  NOT NULL,
    [State]      NVARCHAR (50)  NOT NULL,
    [Nation]     NVARCHAR (50)  NOT NULL,
    [TranspZone] NVARCHAR (50)  NOT NULL
);


GO
PRINT N'Creating [tmp].[ItemsRaw]...';


GO
CREATE TABLE [tmp].[ItemsRaw] (
    [CodItem]      NVARCHAR (50)  NOT NULL,
    [ItemDescr]    NVARCHAR (250) NOT NULL,
    [UnitWeight]   NVARCHAR (50)  NOT NULL,
    [CodPlant]     NVARCHAR (50)  NOT NULL,
    [CodItemGroup] NVARCHAR (50)  NOT NULL,
    [Class01]      NVARCHAR (50)  NOT NULL,
    [Class02]      NVARCHAR (50)  NOT NULL,
    [Class03]      NVARCHAR (50)  NOT NULL,
    [Class04]      NVARCHAR (50)  NOT NULL,
    [Class05]      NVARCHAR (50)  NOT NULL
);


GO
PRINT N'Creating [tmp].[TranspCostRaw]...';


GO
CREATE TABLE [tmp].[TranspCostRaw] (
    [TranspZone] NVARCHAR (50) NOT NULL,
    [TranspCost] NVARCHAR (50) NOT NULL
);


GO
PRINT N'Creating [tmp].[DiesGroupRaw]...';


GO
CREATE TABLE [tmp].[DiesGroupRaw] (
    [CodDiesGroup] NVARCHAR (50) NOT NULL,
    [Price]        NVARCHAR (50) NOT NULL,
    [QtyTot]       NVARCHAR (50) NOT NULL,
    [QtyEOL]       NVARCHAR (50) NOT NULL,
    [ExpLife]      NVARCHAR (50) NOT NULL,
    [EOLLife]      NVARCHAR (50) NOT NULL
);


GO
PRINT N'Creating [tmp].[ExcludeCondFilter]...';


GO
CREATE TABLE [tmp].[ExcludeCondFilter] (
    [TableName] NVARCHAR (50)  NOT NULL,
    [FieldName] NVARCHAR (50)  NOT NULL,
    [WhereCond] NVARCHAR (MAX) NULL,
    CONSTRAINT [PK_ExtFieldsFilter] PRIMARY KEY CLUSTERED ([TableName] ASC, [FieldName] ASC)
);


GO
PRINT N'Creating [tmp].[ProductionLogRaw]...';


GO
CREATE TABLE [tmp].[ProductionLogRaw] (
    [EventStart]  NVARCHAR (50)  NOT NULL,
    [EventEnd]    NVARCHAR (50)  NOT NULL,
    [CodPlant]    NVARCHAR (50)  NOT NULL,
    [ProcessNum]  NVARCHAR (50)  NOT NULL,
    [NrPos]       NVARCHAR (50)  NOT NULL,
    [CodDies]     NVARCHAR (50)  NOT NULL,
    [CodClient]   NVARCHAR (50)  NOT NULL,
    [OrderNum]    NVARCHAR (50)  NOT NULL,
    [BatchNum]    NVARCHAR (50)  NOT NULL,
    [ProcessType] NVARCHAR (50)  NOT NULL,
    [EventType]   NVARCHAR (50)  NOT NULL,
    [RawMat]      NVARCHAR (50)  NOT NULL,
    [CodPackag]   NVARCHAR (50)  NOT NULL,
    [QtyIN]       NVARCHAR (50)  NOT NULL,
    [QtyOUT]      NVARCHAR (50)  NOT NULL,
    [QtyEXT]      NVARCHAR (50)  NOT NULL,
    [NumIN]       NVARCHAR (50)  NOT NULL,
    [NumOUT]      NVARCHAR (50)  NOT NULL,
    [QuotaPlant]  NVARCHAR (50)  NOT NULL,
    [QuotaMan]    NVARCHAR (50)  NOT NULL,
    [Tags]        NVARCHAR (250) NOT NULL,
    [okPr]        BIT            NOT NULL,
    [okQM]        BIT            NOT NULL,
    [okSc]        BIT            NOT NULL,
    [okDi]        BIT            NOT NULL
);


GO
PRINT N'Creating [tmp].[PackagRaw]...';


GO
CREATE TABLE [tmp].[PackagRaw] (
    [CodPackag]  NVARCHAR (50)  NOT NULL,
    [PackagDesc] NVARCHAR (250) NOT NULL,
    [RMCost]     NVARCHAR (50)  NOT NULL,
    [RMWeight]   NVARCHAR (50)  NOT NULL,
    [Tare]       NVARCHAR (50)  NOT NULL,
    [FullWeight] NVARCHAR (50)  NOT NULL
);


GO
PRINT N'Creating [tmp].[OrdersHistRaw]...';


GO
CREATE TABLE [tmp].[OrdersHistRaw] (
    [OrdNum]          NVARCHAR (50) NOT NULL,
    [OrdRow]          NVARCHAR (50) NOT NULL,
    [OrdDate]         NVARCHAR (50) NOT NULL,
    [CodClient]       NVARCHAR (50) NOT NULL,
    [CodItem]         NVARCHAR (50) NOT NULL,
    [RawMat]          NVARCHAR (50) NOT NULL,
    [RawMatCost]      NVARCHAR (50) NOT NULL,
    [BatchQty]        NVARCHAR (50) NOT NULL,
    [CodInco]         NVARCHAR (50) NOT NULL,
    [OrdPrice]        NVARCHAR (50) NOT NULL,
    [RawMatExtraCost] NVARCHAR (50) NOT NULL,
    [PriceOff]        NVARCHAR (50) NOT NULL,
    [OrdQty]          NVARCHAR (50) NOT NULL,
    [ProvvCost]       NVARCHAR (50) NOT NULL
);


GO
PRINT N'Creating [ext].[DiesRaw]...';


GO
CREATE TABLE [ext].[DiesRaw] (
    [CodDies]      NVARCHAR (50)  NOT NULL,
    [HoleNum]      INT            NOT NULL,
    [CodItem]      NVARCHAR (50)  NOT NULL,
    [CodDiesGroup] NVARCHAR (50)  NOT NULL,
    [Price]        DECIMAL (9, 3) NOT NULL,
    [ExpLife]      DECIMAL (9, 2) NOT NULL,
    [ActLife]      DECIMAL (9, 2) NOT NULL,
    [Active]       INT            NOT NULL,
    CONSTRAINT [PK_DiesDet] PRIMARY KEY CLUSTERED ([CodDies] ASC)
);


GO
PRINT N'Creating [ext].[TranspCostRaw]...';


GO
CREATE TABLE [ext].[TranspCostRaw] (
    [TranspZone] NVARCHAR (50)  NOT NULL,
    [TranspCost] DECIMAL (9, 6) NOT NULL,
    CONSTRAINT [PK_TranspCostDet_1] PRIMARY KEY CLUSTERED ([TranspZone] ASC)
);


GO
PRINT N'Creating [ext].[ClientsRaw]...';


GO
CREATE TABLE [ext].[ClientsRaw] (
    [CodClient]  NVARCHAR (50)  NOT NULL,
    [ClientName] NVARCHAR (250) NOT NULL,
    [CodAg]      NVARCHAR (50)  NOT NULL,
    [ZipCode]    NVARCHAR (50)  NOT NULL,
    [City]       NVARCHAR (50)  NOT NULL,
    [State]      NVARCHAR (50)  NOT NULL,
    [Nation]     NVARCHAR (50)  NOT NULL,
    [TranspZone] NVARCHAR (50)  NOT NULL,
    CONSTRAINT [PK_ClientiRaw] PRIMARY KEY CLUSTERED ([CodClient] ASC)
);


GO
PRINT N'Creating [ext].[ProductionLogRaw]...';


GO
CREATE TABLE [ext].[ProductionLogRaw] (
    [EventStart]  DATETIME        NOT NULL,
    [EventEnd]    DATETIME        NOT NULL,
    [CodPlant]    NVARCHAR (50)   NOT NULL,
    [ProcessNum]  NVARCHAR (50)   NOT NULL,
    [NrPos]       NVARCHAR (50)   NOT NULL,
    [CodDies]     NVARCHAR (50)   NOT NULL,
    [CodClient]   NVARCHAR (50)   NOT NULL,
    [OrderNum]    NVARCHAR (50)   NOT NULL,
    [BatchNum]    NVARCHAR (50)   NOT NULL,
    [ProcessType] NVARCHAR (50)   NOT NULL,
    [EventType]   NVARCHAR (50)   NOT NULL,
    [RawMat]      NVARCHAR (50)   NOT NULL,
    [CodPackag]   NVARCHAR (50)   NOT NULL,
    [QtyIN]       DECIMAL (18, 4) NOT NULL,
    [QtyOUT]      DECIMAL (18, 4) NOT NULL,
    [QtyEXT]      DECIMAL (18, 4) NOT NULL,
    [NumIN]       INT             NOT NULL,
    [NumOUT]      INT             NOT NULL,
    [QuotaPlant]  DECIMAL (9, 4)  NOT NULL,
    [QuotaMan]    DECIMAL (9, 4)  NOT NULL,
    [Tags]        NVARCHAR (250)  NOT NULL,
    [okPr]        BIT             NOT NULL,
    [okQM]        BIT             NOT NULL,
    [okSc]        BIT             NOT NULL,
    [okDi]        BIT             NOT NULL,
    CONSTRAINT [PK_ProductionLogRaw] PRIMARY KEY CLUSTERED ([EventStart] ASC, [EventEnd] ASC, [CodPlant] ASC, [ProcessNum] ASC, [NrPos] ASC, [CodDies] ASC)
);


GO
PRINT N'Creating [ext].[ProductionLogRaw_KO]...';


GO
CREATE TABLE [ext].[ProductionLogRaw_KO] (
    [EventStart]    DATETIME        NOT NULL,
    [EventEnd]      DATETIME        NOT NULL,
    [CodPlant]      NVARCHAR (50)   NOT NULL,
    [ProcessNum]    NVARCHAR (50)   NOT NULL,
    [NrPos]         NVARCHAR (50)   NOT NULL,
    [CodDies]       NVARCHAR (50)   NOT NULL,
    [CodClient]     NVARCHAR (50)   NOT NULL,
    [OrderNum]      NVARCHAR (50)   NOT NULL,
    [BatchNum]      NVARCHAR (50)   NOT NULL,
    [ProcessType]   NVARCHAR (50)   NOT NULL,
    [EventType]     NVARCHAR (50)   NOT NULL,
    [RawMat]        NVARCHAR (50)   NOT NULL,
    [CodPackag]     NVARCHAR (50)   NOT NULL,
    [QtyIN]         DECIMAL (18, 4) NOT NULL,
    [QtyOUT]        DECIMAL (18, 4) NOT NULL,
    [QtyEXT]        DECIMAL (18, 4) NOT NULL,
    [NumIN]         INT             NOT NULL,
    [NumOUT]        INT             NOT NULL,
    [QuotaPlant]    DECIMAL (9, 4)  NOT NULL,
    [QuotaMan]      DECIMAL (9, 4)  NOT NULL,
    [Tags]          NVARCHAR (250)  NOT NULL,
    [okPr]          BIT             NOT NULL,
    [okQM]          BIT             NOT NULL,
    [okSc]          BIT             NOT NULL,
    [okDi]          BIT             NOT NULL,
    [ImportDateExt] DATETIME        NULL,
    CONSTRAINT [PK_ProductionLogRaw_KO] PRIMARY KEY CLUSTERED ([EventStart] ASC, [EventEnd] ASC, [CodPlant] ASC, [ProcessNum] ASC, [NrPos] ASC, [CodDies] ASC)
);


GO
PRINT N'Creating [ext].[ItemsRaw]...';


GO
CREATE TABLE [ext].[ItemsRaw] (
    [CodItem]      NVARCHAR (50)  NOT NULL,
    [ItemDescr]    NVARCHAR (250) NOT NULL,
    [UnitWeight]   DECIMAL (9, 3) NOT NULL,
    [CodPlant]     NVARCHAR (50)  NOT NULL,
    [CodItemGroup] NVARCHAR (50)  NOT NULL,
    [Class01]      NVARCHAR (50)  NOT NULL,
    [Class02]      NVARCHAR (50)  NOT NULL,
    [Class03]      NVARCHAR (50)  NOT NULL,
    [Class04]      NVARCHAR (50)  NOT NULL,
    [Class05]      NVARCHAR (50)  NOT NULL,
    CONSTRAINT [PK_ArticoliRaw] PRIMARY KEY CLUSTERED ([CodItem] ASC)
);


GO
PRINT N'Creating [ext].[PackagRaw]...';


GO
CREATE TABLE [ext].[PackagRaw] (
    [CodPackag]  NVARCHAR (50)  NOT NULL,
    [PackagDesc] NVARCHAR (250) NOT NULL,
    [RMCost]     DECIMAL (9, 3) NOT NULL,
    [RMWeight]   DECIMAL (9, 4) NOT NULL,
    [Tare]       DECIMAL (9, 4) NOT NULL,
    [FullWeight] DECIMAL (9, 4) NOT NULL,
    CONSTRAINT [PK_PackagDet] PRIMARY KEY CLUSTERED ([CodPackag] ASC)
);


GO
PRINT N'Creating [ext].[DiesGroupRaw]...';


GO
CREATE TABLE [ext].[DiesGroupRaw] (
    [CodDiesGroup] NVARCHAR (50)  NOT NULL,
    [Price]        DECIMAL (9, 3) NOT NULL,
    [QtyTot]       INT            NOT NULL,
    [QtyEOL]       INT            NOT NULL,
    [ExpLife]      DECIMAL (9, 3) NOT NULL,
    [EOLLife]      DECIMAL (9, 3) NOT NULL,
    CONSTRAINT [PK_DiesGroupRaw] PRIMARY KEY CLUSTERED ([CodDiesGroup] ASC)
);


GO
PRINT N'Creating [ext].[OrdersHistRaw]...';


GO
CREATE TABLE [ext].[OrdersHistRaw] (
    [OrdNum]          NVARCHAR (50)   NOT NULL,
    [OrdRow]          NVARCHAR (50)   NOT NULL,
    [OrdDate]         SMALLDATETIME   NOT NULL,
    [CodClient]       NVARCHAR (50)   NOT NULL,
    [CodItem]         NVARCHAR (50)   NOT NULL,
    [RawMat]          NVARCHAR (50)   NOT NULL,
    [RawMatCost]      DECIMAL (18, 6) NOT NULL,
    [BatchQty]        INT             NOT NULL,
    [CodInco]         NVARCHAR (5)    NOT NULL,
    [OrdPrice]        DECIMAL (9, 6)  NOT NULL,
    [RawMatExtraCost] DECIMAL (18, 6) NOT NULL,
    [PriceOff]        DECIMAL (9, 6)  NOT NULL,
    [OrdQty]          INT             NOT NULL,
    [ProvvCost]       DECIMAL (9, 6)  NOT NULL,
    CONSTRAINT [PK_OrdersHistRaw] PRIMARY KEY CLUSTERED ([OrdNum] ASC, [OrdRow] ASC)
);


GO
PRINT N'Creating [ext].[RcdItem]...';


GO
CREATE TABLE [ext].[RcdItem] (
    [CodItem]      NVARCHAR (50)  NOT NULL,
    [CodItemRcd]   NVARCHAR (50)  NOT NULL,
    [ItemDescrRcd] NVARCHAR (250) NOT NULL,
    [CodPlantRcd]  NVARCHAR (50)  NOT NULL,
    CONSTRAINT [PK_RcdItem] PRIMARY KEY CLUSTERED ([CodItem] ASC)
);


GO
PRINT N'Creating [ext].[RcdClient]...';


GO
CREATE TABLE [ext].[RcdClient] (
    [CodClient]     NVARCHAR (50)  NOT NULL,
    [CodClientRcd]  NVARCHAR (50)  NOT NULL,
    [CodAgRcd]      NVARCHAR (50)  NOT NULL,
    [ClientNameRcd] NVARCHAR (250) NULL,
    CONSTRAINT [PK_RcdClient] PRIMARY KEY CLUSTERED ([CodClient] ASC)
);


GO
PRINT N'Creating [ext].[RcdClass02]...';


GO
CREATE TABLE [ext].[RcdClass02] (
    [CodClass02]    NVARCHAR (50) NOT NULL,
    [CodClass02Rcd] NVARCHAR (50) NOT NULL,
    CONSTRAINT [PK_RcdClass02] PRIMARY KEY CLUSTERED ([CodClass02] ASC)
);


GO
PRINT N'Creating [ext].[RcdClass01]...';


GO
CREATE TABLE [ext].[RcdClass01] (
    [CodClass01]    NVARCHAR (50) NOT NULL,
    [CodClass01Rcd] NVARCHAR (50) NOT NULL,
    CONSTRAINT [PK_RcdClass] PRIMARY KEY CLUSTERED ([CodClass01] ASC)
);


GO
PRINT N'Creating [ext].[RcdPlants]...';


GO
CREATE TABLE [ext].[RcdPlants] (
    [CodPlant]    NVARCHAR (50) NOT NULL,
    [CodPlantRcd] NVARCHAR (50) NOT NULL,
    CONSTRAINT [PK_RcdPlants] PRIMARY KEY CLUSTERED ([CodPlant] ASC)
);


GO
PRINT N'Creating [ext].[RcdPackage]...';


GO
CREATE TABLE [ext].[RcdPackage] (
    [CodPackag]     NVARCHAR (50)  NOT NULL,
    [PackagDescRcd] NVARCHAR (250) NOT NULL,
    [PackagDesc]    NVARCHAR (250) NULL,
    CONSTRAINT [PK_RcdPackage] PRIMARY KEY CLUSTERED ([CodPackag] ASC)
);


GO
PRINT N'Creating DF_QuoteExtra_QuoteType...';


GO
ALTER TABLE [dbo].[QuoteOC]
    ADD CONSTRAINT [DF_QuoteExtra_QuoteType] DEFAULT ('Q') FOR [QuoteType];


GO
PRINT N'Creating DF_QuoteExtra_QuoteRev...';


GO
ALTER TABLE [dbo].[QuoteOC]
    ADD CONSTRAINT [DF_QuoteExtra_QuoteRev] DEFAULT ((0)) FOR [QuoteRev];


GO
PRINT N'Creating DF_QuoteExtra_ResType...';


GO
ALTER TABLE [dbo].[QuoteOC]
    ADD CONSTRAINT [DF_QuoteExtra_ResType] DEFAULT ((0)) FOR [ProcessNum];


GO
PRINT N'Creating DF_QuoteExtra_Class01...';


GO
ALTER TABLE [dbo].[QuoteOC]
    ADD CONSTRAINT [DF_QuoteExtra_Class01] DEFAULT ('') FOR [Class01];


GO
PRINT N'Creating DF_QuoteExtra_Class02...';


GO
ALTER TABLE [dbo].[QuoteOC]
    ADD CONSTRAINT [DF_QuoteExtra_Class02] DEFAULT ('') FOR [Class02];


GO
PRINT N'Creating DF_QuoteExtra_Class03...';


GO
ALTER TABLE [dbo].[QuoteOC]
    ADD CONSTRAINT [DF_QuoteExtra_Class03] DEFAULT ('') FOR [Class03];


GO
PRINT N'Creating DF_QuoteExtra_Class04...';


GO
ALTER TABLE [dbo].[QuoteOC]
    ADD CONSTRAINT [DF_QuoteExtra_Class04] DEFAULT ('') FOR [Class04];


GO
PRINT N'Creating DF_QuoteExtra_Class05...';


GO
ALTER TABLE [dbo].[QuoteOC]
    ADD CONSTRAINT [DF_QuoteExtra_Class05] DEFAULT ('') FOR [Class05];


GO
PRINT N'Creating DF_QuoteExtra_TotQty...';


GO
ALTER TABLE [dbo].[QuoteOC]
    ADD CONSTRAINT [DF_QuoteExtra_TotQty] DEFAULT ((1)) FOR [TotQty];


GO
PRINT N'Creating DF_QuoteExtra_TotCost...';


GO
ALTER TABLE [dbo].[QuoteOC]
    ADD CONSTRAINT [DF_QuoteExtra_TotCost] DEFAULT ((0)) FOR [TotCost];


GO
PRINT N'Creating DF_QuoteExtra_Quota...';


GO
ALTER TABLE [dbo].[QuoteOC]
    ADD CONSTRAINT [DF_QuoteExtra_Quota] DEFAULT ((1)) FOR [Quota];


GO
PRINT N'Creating DF_QuoteOC_valid...';


GO
ALTER TABLE [dbo].[QuoteOC]
    ADD CONSTRAINT [DF_QuoteOC_valid] DEFAULT ((1)) FOR [valid];


GO
PRINT N'Creating DF_QuoteWorkExt_QuoteType...';


GO
ALTER TABLE [dbo].[QuoteWorkExt]
    ADD CONSTRAINT [DF_QuoteWorkExt_QuoteType] DEFAULT ('Q') FOR [QuoteType];


GO
PRINT N'Creating DF_QuoteWorkExt_QuoteRev...';


GO
ALTER TABLE [dbo].[QuoteWorkExt]
    ADD CONSTRAINT [DF_QuoteWorkExt_QuoteRev] DEFAULT ((0)) FOR [QuoteRev];


GO
PRINT N'Creating DF_QuoteWorkExt_FC4UG...';


GO
ALTER TABLE [dbo].[QuoteWorkExt]
    ADD CONSTRAINT [DF_QuoteWorkExt_FC4UG] DEFAULT ((0)) FOR [EWC4UG];


GO
PRINT N'Creating DF_QuoteWorkExt_EWC4UG1...';


GO
ALTER TABLE [dbo].[QuoteWorkExt]
    ADD CONSTRAINT [DF_QuoteWorkExt_EWC4UG1] DEFAULT ((0)) FOR [UM];


GO
PRINT N'Creating DF_QuoteWorkExt_valid...';


GO
ALTER TABLE [dbo].[QuoteWorkExt]
    ADD CONSTRAINT [DF_QuoteWorkExt_valid] DEFAULT ((1)) FOR [valid];


GO
PRINT N'Creating DF_Package2Item_TotQty...';


GO
ALTER TABLE [dbo].[Package2Item]
    ADD CONSTRAINT [DF_Package2Item_TotQty] DEFAULT ((0)) FOR [TotQta];


GO
PRINT N'Creating DF_Package2Item_Weight...';


GO
ALTER TABLE [dbo].[Package2Item]
    ADD CONSTRAINT [DF_Package2Item_Weight] DEFAULT ((0)) FOR [Weight];


GO
PRINT N'Creating DF_Package2Item_Tare...';


GO
ALTER TABLE [dbo].[Package2Item]
    ADD CONSTRAINT [DF_Package2Item_Tare] DEFAULT ((0)) FOR [Tare];


GO
PRINT N'Creating DF_Package2Item_NumImb...';


GO
ALTER TABLE [dbo].[Package2Item]
    ADD CONSTRAINT [DF_Package2Item_NumImb] DEFAULT ((0)) FOR [NumImb];


GO
PRINT N'Creating DF_Package2Item_Durata...';


GO
ALTER TABLE [dbo].[Package2Item]
    ADD CONSTRAINT [DF_Package2Item_Durata] DEFAULT ((0)) FOR [Durata];


GO
PRINT N'Creating DF_Package2ItemClient_TotQty...';


GO
ALTER TABLE [dbo].[Package2ItemClient]
    ADD CONSTRAINT [DF_Package2ItemClient_TotQty] DEFAULT ((0)) FOR [TotQta];


GO
PRINT N'Creating DF_Package2ItemClient_Weight...';


GO
ALTER TABLE [dbo].[Package2ItemClient]
    ADD CONSTRAINT [DF_Package2ItemClient_Weight] DEFAULT ((0)) FOR [Weight];


GO
PRINT N'Creating DF_Package2ItemClient_Tare...';


GO
ALTER TABLE [dbo].[Package2ItemClient]
    ADD CONSTRAINT [DF_Package2ItemClient_Tare] DEFAULT ((0)) FOR [Tare];


GO
PRINT N'Creating DF_Package2ItemClient_NumImb...';


GO
ALTER TABLE [dbo].[Package2ItemClient]
    ADD CONSTRAINT [DF_Package2ItemClient_NumImb] DEFAULT ((0)) FOR [NumImb];


GO
PRINT N'Creating DF_Package2ItemClient_Durata...';


GO
ALTER TABLE [dbo].[Package2ItemClient]
    ADD CONSTRAINT [DF_Package2ItemClient_Durata] DEFAULT ((0)) FOR [Durata];


GO
PRINT N'Creating DF_TabImbArt_NumImb...';


GO
ALTER TABLE [dbo].[TabImbArt]
    ADD CONSTRAINT [DF_TabImbArt_NumImb] DEFAULT ((0)) FOR [NumImb];


GO
PRINT N'Creating DF_TabImbArt_TotOut...';


GO
ALTER TABLE [dbo].[TabImbArt]
    ADD CONSTRAINT [DF_TabImbArt_TotOut] DEFAULT ((0)) FOR [TotOut];


GO
PRINT N'Creating DF_TabImbArt_Durata...';


GO
ALTER TABLE [dbo].[TabImbArt]
    ADD CONSTRAINT [DF_TabImbArt_Durata] DEFAULT ((0)) FOR [Durata];


GO
PRINT N'Creating DF_PlantsDet_OH...';


GO
ALTER TABLE [dbo].[PlantsDet]
    ADD CONSTRAINT [DF_PlantsDet_OH] DEFAULT ((1)) FOR [Charge];


GO
PRINT N'Creating DF_RevHistory_RevType...';


GO
ALTER TABLE [dbo].[RevHistory]
    ADD CONSTRAINT [DF_RevHistory_RevType] DEFAULT (N'P') FOR [RevType];


GO
PRINT N'Creating DF_RevHistory_RevNum...';


GO
ALTER TABLE [dbo].[RevHistory]
    ADD CONSTRAINT [DF_RevHistory_RevNum] DEFAULT ((0)) FOR [RevNum];


GO
PRINT N'Creating DF_RevHistory_Description...';


GO
ALTER TABLE [dbo].[RevHistory]
    ADD CONSTRAINT [DF_RevHistory_Description] DEFAULT ('') FOR [Description];


GO
PRINT N'Creating DF_DiesGroupDet_ExpLife...';


GO
ALTER TABLE [dbo].[DiesGroupDet]
    ADD CONSTRAINT [DF_DiesGroupDet_ExpLife] DEFAULT ((1)) FOR [ExpLife];


GO
PRINT N'Creating DF_DiesGroupDet_EOLLife...';


GO
ALTER TABLE [dbo].[DiesGroupDet]
    ADD CONSTRAINT [DF_DiesGroupDet_EOLLife] DEFAULT ((1)) FOR [EOLLife];


GO
PRINT N'Creating DF_Cost2Plant_VC...';


GO
ALTER TABLE [dbo].[Cost2Plant]
    ADD CONSTRAINT [DF_Cost2Plant_VC] DEFAULT ((0)) FOR [VC];


GO
PRINT N'Creating DF_Cost2Plant_OH...';


GO
ALTER TABLE [dbo].[Cost2Plant]
    ADD CONSTRAINT [DF_Cost2Plant_OH] DEFAULT ((0)) FOR [OH];


GO
PRINT N'Creating DF_Cost2Plant_OH1...';


GO
ALTER TABLE [dbo].[Cost2Plant]
    ADD CONSTRAINT [DF_Cost2Plant_OH1] DEFAULT ((0)) FOR [SC];


GO
PRINT N'Creating DF_Cost2Plant_QuotaPlantStd...';


GO
ALTER TABLE [dbo].[Cost2Plant]
    ADD CONSTRAINT [DF_Cost2Plant_QuotaPlantStd] DEFAULT ((0)) FOR [QuotaPlantStd];


GO
PRINT N'Creating DF_Cost2Plant_QuotaManStd...';


GO
ALTER TABLE [dbo].[Cost2Plant]
    ADD CONSTRAINT [DF_Cost2Plant_QuotaManStd] DEFAULT ((0)) FOR [QuotaManStd];


GO
PRINT N'Creating DF_ClientDet_Class01...';


GO
ALTER TABLE [dbo].[ClientDet]
    ADD CONSTRAINT [DF_ClientDet_Class01] DEFAULT ('') FOR [TranspZone];


GO
PRINT N'Creating DF_AgentsDet_QuotaPerc...';


GO
ALTER TABLE [dbo].[AgentsDet]
    ADD CONSTRAINT [DF_AgentsDet_QuotaPerc] DEFAULT ((0)) FOR [QuotaProvvAg];


GO
PRINT N'Creating DF_Utilities_unitCost...';


GO
ALTER TABLE [dbo].[Utilities]
    ADD CONSTRAINT [DF_Utilities_unitCost] DEFAULT ((0)) FOR [UnitCost];


GO
PRINT N'Creating DF_Incoterms_HasTC...';


GO
ALTER TABLE [dbo].[Incoterms]
    ADD CONSTRAINT [DF_Incoterms_HasTC] DEFAULT ((0)) FOR [HasTC];


GO
PRINT N'Creating DF_Table_1_ClassCli01...';


GO
ALTER TABLE [dbo].[TranspCostDet]
    ADD CONSTRAINT [DF_Table_1_ClassCli01] DEFAULT ('') FOR [TranspZone];


GO
PRINT N'Creating DF_QuoteRM_QuoteType...';


GO
ALTER TABLE [dbo].[QuoteRM]
    ADD CONSTRAINT [DF_QuoteRM_QuoteType] DEFAULT ('Q') FOR [QuoteType];


GO
PRINT N'Creating DF_QuoteRM_QuoteRev...';


GO
ALTER TABLE [dbo].[QuoteRM]
    ADD CONSTRAINT [DF_QuoteRM_QuoteRev] DEFAULT ((0)) FOR [QuoteRev];


GO
PRINT N'Creating DF_QuoteRM_RawMatCost...';


GO
ALTER TABLE [dbo].[QuoteRM]
    ADD CONSTRAINT [DF_QuoteRM_RawMatCost] DEFAULT ((0)) FOR [RawMatCost];


GO
PRINT N'Creating DF_QuoteRM_RawMatExtraCost...';


GO
ALTER TABLE [dbo].[QuoteRM]
    ADD CONSTRAINT [DF_QuoteRM_RawMatExtraCost] DEFAULT ((0)) FOR [RawMatExtraCost];


GO
PRINT N'Creating DF_QuoteRM_CodPackag...';


GO
ALTER TABLE [dbo].[QuoteRM]
    ADD CONSTRAINT [DF_QuoteRM_CodPackag] DEFAULT ((0)) FOR [CodPackag];


GO
PRINT N'Creating DF_QuoteRM_ConvRatio...';


GO
ALTER TABLE [dbo].[QuoteRM]
    ADD CONSTRAINT [DF_QuoteRM_ConvRatio] DEFAULT ((1)) FOR [FCR];


GO
PRINT N'Creating DF_QuoteRM_valid...';


GO
ALTER TABLE [dbo].[QuoteRM]
    ADD CONSTRAINT [DF_QuoteRM_valid] DEFAULT ((1)) FOR [valid];


GO
PRINT N'Creating DF_ItemDet_Class01...';


GO
ALTER TABLE [dbo].[ItemDet]
    ADD CONSTRAINT [DF_ItemDet_Class01] DEFAULT ('') FOR [Class01];


GO
PRINT N'Creating DF_ItemDet_Class02...';


GO
ALTER TABLE [dbo].[ItemDet]
    ADD CONSTRAINT [DF_ItemDet_Class02] DEFAULT ('') FOR [Class02];


GO
PRINT N'Creating DF_ItemDet_Class03...';


GO
ALTER TABLE [dbo].[ItemDet]
    ADD CONSTRAINT [DF_ItemDet_Class03] DEFAULT ('') FOR [Class03];


GO
PRINT N'Creating DF_ItemDet_Class04...';


GO
ALTER TABLE [dbo].[ItemDet]
    ADD CONSTRAINT [DF_ItemDet_Class04] DEFAULT ('') FOR [Class04];


GO
PRINT N'Creating DF_ItemDet_Class05...';


GO
ALTER TABLE [dbo].[ItemDet]
    ADD CONSTRAINT [DF_ItemDet_Class05] DEFAULT ('') FOR [Class05];


GO
PRINT N'Creating DF_Package2_TotQty...';


GO
ALTER TABLE [dbo].[Package2]
    ADD CONSTRAINT [DF_Package2_TotQty] DEFAULT ((0)) FOR [TotQta];


GO
PRINT N'Creating DF_Package2_Weight...';


GO
ALTER TABLE [dbo].[Package2]
    ADD CONSTRAINT [DF_Package2_Weight] DEFAULT ((0)) FOR [Weight];


GO
PRINT N'Creating DF_Package2_Tare...';


GO
ALTER TABLE [dbo].[Package2]
    ADD CONSTRAINT [DF_Package2_Tare] DEFAULT ((0)) FOR [Tare];


GO
PRINT N'Creating DF_Package2_NumImb...';


GO
ALTER TABLE [dbo].[Package2]
    ADD CONSTRAINT [DF_Package2_NumImb] DEFAULT ((0)) FOR [NumImb];


GO
PRINT N'Creating DF_Package2_Durata...';


GO
ALTER TABLE [dbo].[Package2]
    ADD CONSTRAINT [DF_Package2_Durata] DEFAULT ((0)) FOR [Durata];


GO
PRINT N'Creating DF_TabImbGrp_NumImb...';


GO
ALTER TABLE [dbo].[TabImbGrp]
    ADD CONSTRAINT [DF_TabImbGrp_NumImb] DEFAULT ((0)) FOR [NumImb];


GO
PRINT N'Creating DF_TabImbGrp_TotOut...';


GO
ALTER TABLE [dbo].[TabImbGrp]
    ADD CONSTRAINT [DF_TabImbGrp_TotOut] DEFAULT ((0)) FOR [TotOut];


GO
PRINT N'Creating DF_TabImbGrp_Durata...';


GO
ALTER TABLE [dbo].[TabImbGrp]
    ADD CONSTRAINT [DF_TabImbGrp_Durata] DEFAULT ((0)) FOR [Durata];


GO
PRINT N'Creating DF_DiesDet_Price...';


GO
ALTER TABLE [dbo].[DiesDet]
    ADD CONSTRAINT [DF_DiesDet_Price] DEFAULT ((0)) FOR [Price];


GO
PRINT N'Creating DF_DiesDet_Price1...';


GO
ALTER TABLE [dbo].[DiesDet]
    ADD CONSTRAINT [DF_DiesDet_Price1] DEFAULT ((0)) FOR [TestCost];


GO
PRINT N'Creating DF_ProductionLog_NrPos...';


GO
ALTER TABLE [dbo].[ProductionLog]
    ADD CONSTRAINT [DF_ProductionLog_NrPos] DEFAULT ('') FOR [NrPos];


GO
PRINT N'Creating DF_ProductionLog_okPr...';


GO
ALTER TABLE [dbo].[ProductionLog]
    ADD CONSTRAINT [DF_ProductionLog_okPr] DEFAULT ((1)) FOR [okPr];


GO
PRINT N'Creating DF_ProductionLog_okQM...';


GO
ALTER TABLE [dbo].[ProductionLog]
    ADD CONSTRAINT [DF_ProductionLog_okQM] DEFAULT ((1)) FOR [okQM];


GO
PRINT N'Creating DF_ProductionLog_okSc...';


GO
ALTER TABLE [dbo].[ProductionLog]
    ADD CONSTRAINT [DF_ProductionLog_okSc] DEFAULT ((1)) FOR [okSc];


GO
PRINT N'Creating DF_ProductionLog_okDi...';


GO
ALTER TABLE [dbo].[ProductionLog]
    ADD CONSTRAINT [DF_ProductionLog_okDi] DEFAULT ((1)) FOR [okDi];


GO
PRINT N'Creating DF_QuoteFull_Q_QuoteType...';


GO
ALTER TABLE [dbo].[QuoteFull_Q]
    ADD CONSTRAINT [DF_QuoteFull_Q_QuoteType] DEFAULT ('Q') FOR [QuoteType];


GO
PRINT N'Creating DF_QuoteFull_Q_IdxQState...';


GO
ALTER TABLE [dbo].[QuoteFull_Q]
    ADD CONSTRAINT [DF_QuoteFull_Q_IdxQState] DEFAULT ((0)) FOR [IdxQState];


GO
PRINT N'Creating DF_QuoteFull_Q_TranspZone...';


GO
ALTER TABLE [dbo].[QuoteFull_Q]
    ADD CONSTRAINT [DF_QuoteFull_Q_TranspZone] DEFAULT ('') FOR [TranspZone];


GO
PRINT N'Creating DF_QuoteFull_Q_PriceOff...';


GO
ALTER TABLE [dbo].[QuoteFull_Q]
    ADD CONSTRAINT [DF_QuoteFull_Q_PriceOff] DEFAULT ((0)) FOR [PriceOff];


GO
PRINT N'Creating DF_QuoteFull_Q_DiamDies...';


GO
ALTER TABLE [dbo].[QuoteFull_Q]
    ADD CONSTRAINT [DF_QuoteFull_Q_DiamDies] DEFAULT ((0)) FOR [DiamDies];


GO
PRINT N'Creating DF_QuoteFull_Q_DiesPrice...';


GO
ALTER TABLE [dbo].[QuoteFull_Q]
    ADD CONSTRAINT [DF_QuoteFull_Q_DiesPrice] DEFAULT ((0)) FOR [DiesPrice];


GO
PRINT N'Creating DF_QuoteFull_Q_DiesExpLife...';


GO
ALTER TABLE [dbo].[QuoteFull_Q]
    ADD CONSTRAINT [DF_QuoteFull_Q_DiesExpLife] DEFAULT ((0)) FOR [DiesExpLife];


GO
PRINT N'Creating DF_QuoteFull_Q_DiesByClass...';


GO
ALTER TABLE [dbo].[QuoteFull_Q]
    ADD CONSTRAINT [DF_QuoteFull_Q_DiesByClass] DEFAULT ((0)) FOR [DiesByClass];


GO
PRINT N'Creating DF_QuoteFull_Q_valid...';


GO
ALTER TABLE [dbo].[QuoteFull_Q]
    ADD CONSTRAINT [DF_QuoteFull_Q_valid] DEFAULT ((1)) FOR [valid];


GO
PRINT N'Creating DF_QuoteFull_Q_errorScore...';


GO
ALTER TABLE [dbo].[QuoteFull_Q]
    ADD CONSTRAINT [DF_QuoteFull_Q_errorScore] DEFAULT ((0)) FOR [errorScore];


GO
PRINT N'Creating DF_QuoteList_QuoteType...';


GO
ALTER TABLE [dbo].[QuoteList]
    ADD CONSTRAINT [DF_QuoteList_QuoteType] DEFAULT ('Q') FOR [QuoteType];


GO
PRINT N'Creating DF_QuoteList_QuoteRev...';


GO
ALTER TABLE [dbo].[QuoteList]
    ADD CONSTRAINT [DF_QuoteList_QuoteRev] DEFAULT ((0)) FOR [QuoteRev];


GO
PRINT N'Creating DF_QuoteList_State...';


GO
ALTER TABLE [dbo].[QuoteList]
    ADD CONSTRAINT [DF_QuoteList_State] DEFAULT ((0)) FOR [IdxQState];


GO
PRINT N'Creating DF_QuoteList_CodItem...';


GO
ALTER TABLE [dbo].[QuoteList]
    ADD CONSTRAINT [DF_QuoteList_CodItem] DEFAULT ('') FOR [CodItem];


GO
PRINT N'Creating DF_QuoteList_CodItemGroup...';


GO
ALTER TABLE [dbo].[QuoteList]
    ADD CONSTRAINT [DF_QuoteList_CodItemGroup] DEFAULT ('') FOR [CodItemGroup];


GO
PRINT N'Creating DF_QuoteList_UnitWeight...';


GO
ALTER TABLE [dbo].[QuoteList]
    ADD CONSTRAINT [DF_QuoteList_UnitWeight] DEFAULT ((0)) FOR [UnitWeight];


GO
PRINT N'Creating DF_QuoteList_BathQty...';


GO
ALTER TABLE [dbo].[QuoteList]
    ADD CONSTRAINT [DF_QuoteList_BathQty] DEFAULT ((0)) FOR [BatchQty];


GO
PRINT N'Creating DF_QuoteList_Note...';


GO
ALTER TABLE [dbo].[QuoteList]
    ADD CONSTRAINT [DF_QuoteList_Note] DEFAULT ('') FOR [Note];


GO
PRINT N'Creating DF_QuoteList_OrdPrice1...';


GO
ALTER TABLE [dbo].[QuoteList]
    ADD CONSTRAINT [DF_QuoteList_OrdPrice1] DEFAULT ((0)) FOR [PriceOff];


GO
PRINT N'Creating DF_QuoteList_OrdNum...';


GO
ALTER TABLE [dbo].[QuoteList]
    ADD CONSTRAINT [DF_QuoteList_OrdNum] DEFAULT ((0)) FOR [OrdNum];


GO
PRINT N'Creating DF_QuoteList_OrdRow...';


GO
ALTER TABLE [dbo].[QuoteList]
    ADD CONSTRAINT [DF_QuoteList_OrdRow] DEFAULT ((0)) FOR [OrdRow];


GO
PRINT N'Creating DF_QuoteList_PriceOff1...';


GO
ALTER TABLE [dbo].[QuoteList]
    ADD CONSTRAINT [DF_QuoteList_PriceOff1] DEFAULT ((0)) FOR [OrdPrice];


GO
PRINT N'Creating DF_QuoteList_OrderQty...';


GO
ALTER TABLE [dbo].[QuoteList]
    ADD CONSTRAINT [DF_QuoteList_OrderQty] DEFAULT ((0)) FOR [OrdQty];


GO
PRINT N'Creating DF_QuoteList_valid...';


GO
ALTER TABLE [dbo].[QuoteList]
    ADD CONSTRAINT [DF_QuoteList_valid] DEFAULT ((1)) FOR [valid];


GO
PRINT N'Creating DF_QuoteList_errorScore...';


GO
ALTER TABLE [dbo].[QuoteList]
    ADD CONSTRAINT [DF_QuoteList_errorScore] DEFAULT ((0)) FOR [errorScore];


GO
PRINT N'Creating DF_QuoteList_UserCreaz...';


GO
ALTER TABLE [dbo].[QuoteList]
    ADD CONSTRAINT [DF_QuoteList_UserCreaz] DEFAULT ('') FOR [UserCreaz];


GO
PRINT N'Creating DF_QuoteList_DataCreaz...';


GO
ALTER TABLE [dbo].[QuoteList]
    ADD CONSTRAINT [DF_QuoteList_DataCreaz] DEFAULT (getdate()) FOR [DataCreaz];


GO
PRINT N'Creating DF_QuoteList_UserMod...';


GO
ALTER TABLE [dbo].[QuoteList]
    ADD CONSTRAINT [DF_QuoteList_UserMod] DEFAULT ('') FOR [UserMod];


GO
PRINT N'Creating DF_QuoteList_DataMod...';


GO
ALTER TABLE [dbo].[QuoteList]
    ADD CONSTRAINT [DF_QuoteList_DataMod] DEFAULT (getdate()) FOR [DataMod];


GO
PRINT N'Creating DF_QuoteParam_QuoteType...';


GO
ALTER TABLE [dbo].[QuoteParam]
    ADD CONSTRAINT [DF_QuoteParam_QuoteType] DEFAULT ('Q') FOR [QuoteType];


GO
PRINT N'Creating DF_QuoteParam_QuoteRev...';


GO
ALTER TABLE [dbo].[QuoteParam]
    ADD CONSTRAINT [DF_QuoteParam_QuoteRev] DEFAULT ((0)) FOR [QuoteRev];


GO
PRINT N'Creating DF_QuoteParam_ProcessNum...';


GO
ALTER TABLE [dbo].[QuoteParam]
    ADD CONSTRAINT [DF_QuoteParam_ProcessNum] DEFAULT ((0)) FOR [ProcessNum];


GO
PRINT N'Creating DF_QuoteParam_Parameter...';


GO
ALTER TABLE [dbo].[QuoteParam]
    ADD CONSTRAINT [DF_QuoteParam_Parameter] DEFAULT ('') FOR [Parameter];


GO
PRINT N'Creating DF_QuoteWorkInt_QuoteType...';


GO
ALTER TABLE [dbo].[QuoteWorkInt]
    ADD CONSTRAINT [DF_QuoteWorkInt_QuoteType] DEFAULT ('Q') FOR [QuoteType];


GO
PRINT N'Creating DF_QuoteWorkInt_QuoteRev...';


GO
ALTER TABLE [dbo].[QuoteWorkInt]
    ADD CONSTRAINT [DF_QuoteWorkInt_QuoteRev] DEFAULT ((0)) FOR [QuoteRev];


GO
PRINT N'Creating DF_QuoteWorkInt_WorkType...';


GO
ALTER TABLE [dbo].[QuoteWorkInt]
    ADD CONSTRAINT [DF_QuoteWorkInt_WorkType] DEFAULT ((0)) FOR [ProcessNum];


GO
PRINT N'Creating DF_QuoteWorkInt_Prod_LUK...';


GO
ALTER TABLE [dbo].[QuoteWorkInt]
    ADD CONSTRAINT [DF_QuoteWorkInt_Prod_LUK] DEFAULT ('') FOR [Class01];


GO
PRINT N'Creating DF_QuoteWorkInt_Class011...';


GO
ALTER TABLE [dbo].[QuoteWorkInt]
    ADD CONSTRAINT [DF_QuoteWorkInt_Class011] DEFAULT ('') FOR [Class02];


GO
PRINT N'Creating DF_QuoteWorkInt_Class021...';


GO
ALTER TABLE [dbo].[QuoteWorkInt]
    ADD CONSTRAINT [DF_QuoteWorkInt_Class021] DEFAULT ('') FOR [Class03];


GO
PRINT N'Creating DF_QuoteWorkInt_Class031...';


GO
ALTER TABLE [dbo].[QuoteWorkInt]
    ADD CONSTRAINT [DF_QuoteWorkInt_Class031] DEFAULT ('') FOR [Class04];


GO
PRINT N'Creating DF_QuoteWorkInt_Class032...';


GO
ALTER TABLE [dbo].[QuoteWorkInt]
    ADD CONSTRAINT [DF_QuoteWorkInt_Class032] DEFAULT ('') FOR [Class05];


GO
PRINT N'Creating DF_QuoteWorkInt_NetProd...';


GO
ALTER TABLE [dbo].[QuoteWorkInt]
    ADD CONSTRAINT [DF_QuoteWorkInt_NetProd] DEFAULT ((0)) FOR [NetProd];


GO
PRINT N'Creating DF_QuoteWorkInt_TSR...';


GO
ALTER TABLE [dbo].[QuoteWorkInt]
    ADD CONSTRAINT [DF_QuoteWorkInt_TSR] DEFAULT ((0)) FOR [WSR];


GO
PRINT N'Creating DF_QuoteWorkInt_CSR...';


GO
ALTER TABLE [dbo].[QuoteWorkInt]
    ADD CONSTRAINT [DF_QuoteWorkInt_CSR] DEFAULT ((0)) FOR [MSR];


GO
PRINT N'Creating DF_QuoteWorkInt_CSR1...';


GO
ALTER TABLE [dbo].[QuoteWorkInt]
    ADD CONSTRAINT [DF_QuoteWorkInt_CSR1] DEFAULT ((0)) FOR [DSR];


GO
PRINT N'Creating DF_QuoteWorkInt_RUFG...';


GO
ALTER TABLE [dbo].[QuoteWorkInt]
    ADD CONSTRAINT [DF_QuoteWorkInt_RUFG] DEFAULT ((0)) FOR [FC4UG];


GO
PRINT N'Creating DF_QuoteWorkInt_RCFG...';


GO
ALTER TABLE [dbo].[QuoteWorkInt]
    ADD CONSTRAINT [DF_QuoteWorkInt_RCFG] DEFAULT ((0)) FOR [VC4UG];


GO
PRINT N'Creating DF_QuoteWorkInt_VC4UG1...';


GO
ALTER TABLE [dbo].[QuoteWorkInt]
    ADD CONSTRAINT [DF_QuoteWorkInt_VC4UG1] DEFAULT ((0)) FOR [OH4UG];


GO
PRINT N'Creating DF_QuoteWorkInt_VC4UG1_1...';


GO
ALTER TABLE [dbo].[QuoteWorkInt]
    ADD CONSTRAINT [DF_QuoteWorkInt_VC4UG1_1] DEFAULT ((0)) FOR [SC4UG];


GO
PRINT N'Creating DF_QuoteWorkInt_valid...';


GO
ALTER TABLE [dbo].[QuoteWorkInt]
    ADD CONSTRAINT [DF_QuoteWorkInt_valid] DEFAULT ((1)) FOR [valid];


GO
PRINT N'Creating DF_RawMatDet_ProcCost...';


GO
ALTER TABLE [dbo].[RawMatDet]
    ADD CONSTRAINT [DF_RawMatDet_ProcCost] DEFAULT ((0)) FOR [ProcCost];


GO
PRINT N'Creating DF_RawMatDet_ProcYield...';


GO
ALTER TABLE [dbo].[RawMatDet]
    ADD CONSTRAINT [DF_RawMatDet_ProcYield] DEFAULT ((0)) FOR [ProcYield];


GO
PRINT N'Creating DF_RawMatDet_CSR...';


GO
ALTER TABLE [dbo].[RawMatDet]
    ADD CONSTRAINT [DF_RawMatDet_CSR] DEFAULT ((0)) FOR [CSR];


GO
PRINT N'Creating DF_RawMatDet_SSR...';


GO
ALTER TABLE [dbo].[RawMatDet]
    ADD CONSTRAINT [DF_RawMatDet_SSR] DEFAULT ((0)) FOR [SSR];


GO
PRINT N'Creating DF_RawMatDet_SSVA...';


GO
ALTER TABLE [dbo].[RawMatDet]
    ADD CONSTRAINT [DF_RawMatDet_SSVA] DEFAULT ((0)) FOR [SSVA];


GO
PRINT N'Creating DF_RawMatDet_SSVR...';


GO
ALTER TABLE [dbo].[RawMatDet]
    ADD CONSTRAINT [DF_RawMatDet_SSVR] DEFAULT ((0)) FOR [SSVR];


GO
PRINT N'Creating DF_RawMatDet_ExtraMatCost...';


GO
ALTER TABLE [dbo].[RawMatDet]
    ADD CONSTRAINT [DF_RawMatDet_ExtraMatCost] DEFAULT ((0)) FOR [ExtraMatCost];


GO
PRINT N'Creating DF_RawMatDet_ExtraServCost...';


GO
ALTER TABLE [dbo].[RawMatDet]
    ADD CONSTRAINT [DF_RawMatDet_ExtraServCost] DEFAULT ((0)) FOR [ExtraServCost];


GO
PRINT N'Creating DF_OrdersHist_OrdNum...';


GO
ALTER TABLE [dbo].[OrdersHist]
    ADD CONSTRAINT [DF_OrdersHist_OrdNum] DEFAULT ((0)) FOR [OrdNum];


GO
PRINT N'Creating DF_OrdersHist_OrdRow...';


GO
ALTER TABLE [dbo].[OrdersHist]
    ADD CONSTRAINT [DF_OrdersHist_OrdRow] DEFAULT ((0)) FOR [OrdRow];


GO
PRINT N'Creating DF_OrdersHist_OrdDate...';


GO
ALTER TABLE [dbo].[OrdersHist]
    ADD CONSTRAINT [DF_OrdersHist_OrdDate] DEFAULT (getdate()) FOR [OrdDate];


GO
PRINT N'Creating DF_OrdersHist_CodItem...';


GO
ALTER TABLE [dbo].[OrdersHist]
    ADD CONSTRAINT [DF_OrdersHist_CodItem] DEFAULT ('') FOR [CodItem];


GO
PRINT N'Creating DF_OrdersHist_RawMatCost...';


GO
ALTER TABLE [dbo].[OrdersHist]
    ADD CONSTRAINT [DF_OrdersHist_RawMatCost] DEFAULT ((0)) FOR [RawMatCost];


GO
PRINT N'Creating DF_OrdersHist_BatchQty...';


GO
ALTER TABLE [dbo].[OrdersHist]
    ADD CONSTRAINT [DF_OrdersHist_BatchQty] DEFAULT ((0)) FOR [BatchQty];


GO
PRINT N'Creating DF_OrdersHist_OrdPrice...';


GO
ALTER TABLE [dbo].[OrdersHist]
    ADD CONSTRAINT [DF_OrdersHist_OrdPrice] DEFAULT ((0)) FOR [OrdPrice];


GO
PRINT N'Creating DF_OrdersHist_QuoteType...';


GO
ALTER TABLE [dbo].[OrdersHist]
    ADD CONSTRAINT [DF_OrdersHist_QuoteType] DEFAULT ('R') FOR [QuoteType];


GO
PRINT N'Creating DF_OrdersHist_CodQuote...';


GO
ALTER TABLE [dbo].[OrdersHist]
    ADD CONSTRAINT [DF_OrdersHist_CodQuote] DEFAULT ((0)) FOR [CodQuote];


GO
PRINT N'Creating DF_OrdersHist_QuoteRev...';


GO
ALTER TABLE [dbo].[OrdersHist]
    ADD CONSTRAINT [DF_OrdersHist_QuoteRev] DEFAULT ((0)) FOR [QuoteRev];


GO
PRINT N'Creating DF_OrdersHist_ProvvCost...';


GO
ALTER TABLE [dbo].[OrdersHist]
    ADD CONSTRAINT [DF_OrdersHist_ProvvCost] DEFAULT ((0)) FOR [ProvvCost];


GO
PRINT N'Creating DF_PickList_lemma...';


GO
ALTER TABLE [dbo].[PickList]
    ADD CONSTRAINT [DF_PickList_lemma] DEFAULT ('') FOR [Lemma];


GO
PRINT N'Creating DF_PickList_NumOrd...';


GO
ALTER TABLE [dbo].[PickList]
    ADD CONSTRAINT [DF_PickList_NumOrd] DEFAULT ((0)) FOR [NumOrd];


GO
PRINT N'Creating DF_QuoteFull_R_QuoteType...';


GO
ALTER TABLE [dbo].[QuoteFull_R]
    ADD CONSTRAINT [DF_QuoteFull_R_QuoteType] DEFAULT ('Q') FOR [QuoteType];


GO
PRINT N'Creating DF_QuoteFull_R_IdxQState...';


GO
ALTER TABLE [dbo].[QuoteFull_R]
    ADD CONSTRAINT [DF_QuoteFull_R_IdxQState] DEFAULT ((0)) FOR [IdxQState];


GO
PRINT N'Creating DF_QuoteFull_R_TranspZone...';


GO
ALTER TABLE [dbo].[QuoteFull_R]
    ADD CONSTRAINT [DF_QuoteFull_R_TranspZone] DEFAULT ('') FOR [TranspZone];


GO
PRINT N'Creating DF_QuoteFull_R_PriceOff...';


GO
ALTER TABLE [dbo].[QuoteFull_R]
    ADD CONSTRAINT [DF_QuoteFull_R_PriceOff] DEFAULT ((0)) FOR [PriceOff];


GO
PRINT N'Creating DF_QuoteFull_R_DiamDies...';


GO
ALTER TABLE [dbo].[QuoteFull_R]
    ADD CONSTRAINT [DF_QuoteFull_R_DiamDies] DEFAULT ((0)) FOR [DiamDies];


GO
PRINT N'Creating DF_QuoteFull_R_DiesPrice...';


GO
ALTER TABLE [dbo].[QuoteFull_R]
    ADD CONSTRAINT [DF_QuoteFull_R_DiesPrice] DEFAULT ((0)) FOR [DiesPrice];


GO
PRINT N'Creating DF_QuoteFull_R_DiesExpLife...';


GO
ALTER TABLE [dbo].[QuoteFull_R]
    ADD CONSTRAINT [DF_QuoteFull_R_DiesExpLife] DEFAULT ((0)) FOR [DiesExpLife];


GO
PRINT N'Creating DF_QuoteFull_R_DiesByClass...';


GO
ALTER TABLE [dbo].[QuoteFull_R]
    ADD CONSTRAINT [DF_QuoteFull_R_DiesByClass] DEFAULT ((0)) FOR [DiesByClass];


GO
PRINT N'Creating DF_QuoteFull_R_valid...';


GO
ALTER TABLE [dbo].[QuoteFull_R]
    ADD CONSTRAINT [DF_QuoteFull_R_valid] DEFAULT ((1)) FOR [valid];


GO
PRINT N'Creating DF_QuoteFull_R_errorScore...';


GO
ALTER TABLE [dbo].[QuoteFull_R]
    ADD CONSTRAINT [DF_QuoteFull_R_errorScore] DEFAULT ((0)) FOR [errorScore];


GO
PRINT N'Creating DF_QuoteSimPar_QuoteType...';


GO
ALTER TABLE [dbo].[QuoteSimPar]
    ADD CONSTRAINT [DF_QuoteSimPar_QuoteType] DEFAULT ('Q') FOR [QuoteType];


GO
PRINT N'Creating DF_QuoteSimPar_QuoteRev...';


GO
ALTER TABLE [dbo].[QuoteSimPar]
    ADD CONSTRAINT [DF_QuoteSimPar_QuoteRev] DEFAULT ((0)) FOR [QuoteRev];


GO
PRINT N'Creating DF_QuoteSimPar_NomePar...';


GO
ALTER TABLE [dbo].[QuoteSimPar]
    ADD CONSTRAINT [DF_QuoteSimPar_NomePar] DEFAULT ('') FOR [NomePar];


GO
PRINT N'Creating DF_QuoteSimPar_ValParStr...';


GO
ALTER TABLE [dbo].[QuoteSimPar]
    ADD CONSTRAINT [DF_QuoteSimPar_ValParStr] DEFAULT ('') FOR [ValPar];


GO
PRINT N'Creating DF_Table1_Tabella...';


GO
ALTER TABLE [dbo].[ReportPrintTicket]
    ADD CONSTRAINT [DF_Table1_Tabella] DEFAULT ('') FOR [Report];


GO
PRINT N'Creating DF_ReportPrintTicket_Chiave...';


GO
ALTER TABLE [dbo].[ReportPrintTicket]
    ADD CONSTRAINT [DF_ReportPrintTicket_Chiave] DEFAULT ('') FOR [Chiave];


GO
PRINT N'Creating DF_ReportPrintTicket_UserReq...';


GO
ALTER TABLE [dbo].[ReportPrintTicket]
    ADD CONSTRAINT [DF_ReportPrintTicket_UserReq] DEFAULT ('') FOR [UserReq];


GO
PRINT N'Creating DF_ReportPrintTicket_DataReq...';


GO
ALTER TABLE [dbo].[ReportPrintTicket]
    ADD CONSTRAINT [DF_ReportPrintTicket_DataReq] DEFAULT (getdate()) FOR [DataReq];


GO
PRINT N'Creating DF_CostList_DataList...';


GO
ALTER TABLE [dbo].[CostList]
    ADD CONSTRAINT [DF_CostList_DataList] DEFAULT (CONVERT([date],getdate(),0)) FOR [DateList];


GO
PRINT N'Creating DF_CostList_QuoteType...';


GO
ALTER TABLE [dbo].[CostList]
    ADD CONSTRAINT [DF_CostList_QuoteType] DEFAULT ('C') FOR [QuoteType];


GO
PRINT N'Creating DF_CostList_CodQuote...';


GO
ALTER TABLE [dbo].[CostList]
    ADD CONSTRAINT [DF_CostList_CodQuote] DEFAULT ((0)) FOR [CodQuote];


GO
PRINT N'Creating DF_CostList_QuoteRev...';


GO
ALTER TABLE [dbo].[CostList]
    ADD CONSTRAINT [DF_CostList_QuoteRev] DEFAULT ((0)) FOR [QuoteRev];


GO
PRINT N'Creating DF_QuoteFull_S_QuoteType...';


GO
ALTER TABLE [dbo].[QuoteFull_S]
    ADD CONSTRAINT [DF_QuoteFull_S_QuoteType] DEFAULT ('S') FOR [QuoteType];


GO
PRINT N'Creating DF_QuoteFull_S_CodQuote...';


GO
ALTER TABLE [dbo].[QuoteFull_S]
    ADD CONSTRAINT [DF_QuoteFull_S_CodQuote] DEFAULT ((0)) FOR [CodQuote];


GO
PRINT N'Creating DF_QuoteFull_S_QuoteRev...';


GO
ALTER TABLE [dbo].[QuoteFull_S]
    ADD CONSTRAINT [DF_QuoteFull_S_QuoteRev] DEFAULT ((0)) FOR [QuoteRev];


GO
PRINT N'Creating DF_QuoteFull_S_IdxQState...';


GO
ALTER TABLE [dbo].[QuoteFull_S]
    ADD CONSTRAINT [DF_QuoteFull_S_IdxQState] DEFAULT ((0)) FOR [IdxQState];


GO
PRINT N'Creating DF_QuoteFull_S_UnitWeight...';


GO
ALTER TABLE [dbo].[QuoteFull_S]
    ADD CONSTRAINT [DF_QuoteFull_S_UnitWeight] DEFAULT ((0)) FOR [UnitWeight];


GO
PRINT N'Creating DF_QuoteFull_S_BatchQty...';


GO
ALTER TABLE [dbo].[QuoteFull_S]
    ADD CONSTRAINT [DF_QuoteFull_S_BatchQty] DEFAULT ((1)) FOR [BatchQty];


GO
PRINT N'Creating DF_QuoteFull_S_PriceOff...';


GO
ALTER TABLE [dbo].[QuoteFull_S]
    ADD CONSTRAINT [DF_QuoteFull_S_PriceOff] DEFAULT ((0)) FOR [PriceOff];


GO
PRINT N'Creating DF_QuoteFull_S_DiamDies...';


GO
ALTER TABLE [dbo].[QuoteFull_S]
    ADD CONSTRAINT [DF_QuoteFull_S_DiamDies] DEFAULT ((0)) FOR [DiamDies];


GO
PRINT N'Creating DF_QuoteFull_S_HoleNumDies...';


GO
ALTER TABLE [dbo].[QuoteFull_S]
    ADD CONSTRAINT [DF_QuoteFull_S_HoleNumDies] DEFAULT ((1)) FOR [HoleNumDies];


GO
PRINT N'Creating DF_QuoteFull_S_DiesPrice_avg...';


GO
ALTER TABLE [dbo].[QuoteFull_S]
    ADD CONSTRAINT [DF_QuoteFull_S_DiesPrice_avg] DEFAULT ((0)) FOR [DiesPrice_sim];


GO
PRINT N'Creating DF_QuoteFull_S_DiesPrice...';


GO
ALTER TABLE [dbo].[QuoteFull_S]
    ADD CONSTRAINT [DF_QuoteFull_S_DiesPrice] DEFAULT ((0)) FOR [DiesPrice];


GO
PRINT N'Creating DF_QuoteFull_S_TestPrice...';


GO
ALTER TABLE [dbo].[QuoteFull_S]
    ADD CONSTRAINT [DF_QuoteFull_S_TestPrice] DEFAULT ((0)) FOR [SamplePrice];


GO
PRINT N'Creating DF_QuoteFull_S_DiesFullCost...';


GO
ALTER TABLE [dbo].[QuoteFull_S]
    ADD CONSTRAINT [DF_QuoteFull_S_DiesFullCost] DEFAULT ((0)) FOR [DiesFullCost];


GO
PRINT N'Creating DF_QuoteFull_S_DiesPrice1...';


GO
ALTER TABLE [dbo].[QuoteFull_S]
    ADD CONSTRAINT [DF_QuoteFull_S_DiesPrice1] DEFAULT ((0)) FOR [DiesPriceClientQuote];


GO
PRINT N'Creating DF_QuoteFull_S_DiesExpLife...';


GO
ALTER TABLE [dbo].[QuoteFull_S]
    ADD CONSTRAINT [DF_QuoteFull_S_DiesExpLife] DEFAULT ((0)) FOR [DiesExpLife];


GO
PRINT N'Creating DF_QuoteFull_S_DiesEOLife...';


GO
ALTER TABLE [dbo].[QuoteFull_S]
    ADD CONSTRAINT [DF_QuoteFull_S_DiesEOLife] DEFAULT ((0)) FOR [DiesEOLife];


GO
PRINT N'Creating DF_QuoteFull_S_DiesTecLife...';


GO
ALTER TABLE [dbo].[QuoteFull_S]
    ADD CONSTRAINT [DF_QuoteFull_S_DiesTecLife] DEFAULT ((1)) FOR [DiesTecLife];


GO
PRINT N'Creating DF_QuoteFull_S_DiesCommLife1...';


GO
ALTER TABLE [dbo].[QuoteFull_S]
    ADD CONSTRAINT [DF_QuoteFull_S_DiesCommLife1] DEFAULT ((1)) FOR [DiesCommLife];


GO
PRINT N'Creating DF_QuoteFull_S_DiesTecLife1...';


GO
ALTER TABLE [dbo].[QuoteFull_S]
    ADD CONSTRAINT [DF_QuoteFull_S_DiesTecLife1] DEFAULT ((0)) FOR [MonthSalesPrev];


GO
PRINT N'Creating DF_QuoteFull_S_SalesPrevCost...';


GO
ALTER TABLE [dbo].[QuoteFull_S]
    ADD CONSTRAINT [DF_QuoteFull_S_SalesPrevCost] DEFAULT ((0)) FOR [SalesPrevCost];


GO
PRINT N'Creating DF_QuoteFull_S_DiesFinCost...';


GO
ALTER TABLE [dbo].[QuoteFull_S]
    ADD CONSTRAINT [DF_QuoteFull_S_DiesFinCost] DEFAULT ((0)) FOR [DiesFinCost];


GO
PRINT N'Creating DF_QuoteFull_S_ClientQuoteReven...';


GO
ALTER TABLE [dbo].[QuoteFull_S]
    ADD CONSTRAINT [DF_QuoteFull_S_ClientQuoteReven] DEFAULT ((0)) FOR [ClientQuoteReven];


GO
PRINT N'Creating DF_QuoteFull_S_ExtraDiscountDies...';


GO
ALTER TABLE [dbo].[QuoteFull_S]
    ADD CONSTRAINT [DF_QuoteFull_S_ExtraDiscountDies] DEFAULT ((0)) FOR [ExtraDiscountDies];


GO
PRINT N'Creating DF_QuoteFull_S_DiesByClass...';


GO
ALTER TABLE [dbo].[QuoteFull_S]
    ADD CONSTRAINT [DF_QuoteFull_S_DiesByClass] DEFAULT ((0)) FOR [DiesByClass];


GO
PRINT N'Creating DF_QuoteFull_S_NumDiesInList...';


GO
ALTER TABLE [dbo].[QuoteFull_S]
    ADD CONSTRAINT [DF_QuoteFull_S_NumDiesInList] DEFAULT ((0)) FOR [NumDiesInList];


GO
PRINT N'Creating DF_QuoteFull_S_NumDiesExaust...';


GO
ALTER TABLE [dbo].[QuoteFull_S]
    ADD CONSTRAINT [DF_QuoteFull_S_NumDiesExaust] DEFAULT ((0)) FOR [NumDiesExaust];


GO
PRINT N'Creating DF_QuoteFull_S_KgTeo...';


GO
ALTER TABLE [dbo].[QuoteFull_S]
    ADD CONSTRAINT [DF_QuoteFull_S_KgTeo] DEFAULT ((0)) FOR [KgTeo];


GO
PRINT N'Creating DF_QuoteFull_S_NumSMED...';


GO
ALTER TABLE [dbo].[QuoteFull_S]
    ADD CONSTRAINT [DF_QuoteFull_S_NumSMED] DEFAULT ((0)) FOR [NumSMED];


GO
PRINT N'Creating DF_QuoteFull_S_QuotaMan...';


GO
ALTER TABLE [dbo].[QuoteFull_S]
    ADD CONSTRAINT [DF_QuoteFull_S_QuotaMan] DEFAULT ((0)) FOR [QuotaMan];


GO
PRINT N'Creating DF_QuoteFull_S_PRMWeight...';


GO
ALTER TABLE [dbo].[QuoteFull_S]
    ADD CONSTRAINT [DF_QuoteFull_S_PRMWeight] DEFAULT ((0)) FOR [PRMWeight];


GO
PRINT N'Creating DF_QuoteFull_S_PWeight...';


GO
ALTER TABLE [dbo].[QuoteFull_S]
    ADD CONSTRAINT [DF_QuoteFull_S_PWeight] DEFAULT ((0)) FOR [PWeight];


GO
PRINT N'Creating DF_QuoteFull_S_PTare...';


GO
ALTER TABLE [dbo].[QuoteFull_S]
    ADD CONSTRAINT [DF_QuoteFull_S_PTare] DEFAULT ((0)) FOR [PTare];


GO
PRINT N'Creating DF_QuoteFull_S_RawMatCost...';


GO
ALTER TABLE [dbo].[QuoteFull_S]
    ADD CONSTRAINT [DF_QuoteFull_S_RawMatCost] DEFAULT ((0)) FOR [RawMatCost];


GO
PRINT N'Creating DF_QuoteFull_S_RawMatExtraCost...';


GO
ALTER TABLE [dbo].[QuoteFull_S]
    ADD CONSTRAINT [DF_QuoteFull_S_RawMatExtraCost] DEFAULT ((0)) FOR [RawMatExtraCost];


GO
PRINT N'Creating DF_QuoteFull_S_RawMatFullCost...';


GO
ALTER TABLE [dbo].[QuoteFull_S]
    ADD CONSTRAINT [DF_QuoteFull_S_RawMatFullCost] DEFAULT ((0)) FOR [RawMatFullCost];


GO
PRINT N'Creating DF_QuoteFull_S_FSR...';


GO
ALTER TABLE [dbo].[QuoteFull_S]
    ADD CONSTRAINT [DF_QuoteFull_S_FSR] DEFAULT ((0)) FOR [FSR];


GO
PRINT N'Creating DF_QuoteFull_S_ProvvCost...';


GO
ALTER TABLE [dbo].[QuoteFull_S]
    ADD CONSTRAINT [DF_QuoteFull_S_ProvvCost] DEFAULT ((0)) FOR [ProvvCost];


GO
PRINT N'Creating DF_QuoteFull_S_EECost...';


GO
ALTER TABLE [dbo].[QuoteFull_S]
    ADD CONSTRAINT [DF_QuoteFull_S_EECost] DEFAULT ((0)) FOR [EECost];


GO
PRINT N'Creating DF_QuoteFull_S_GasCost...';


GO
ALTER TABLE [dbo].[QuoteFull_S]
    ADD CONSTRAINT [DF_QuoteFull_S_GasCost] DEFAULT ((0)) FOR [GasCost];


GO
PRINT N'Creating DF_QuoteFull_S_DiesCost...';


GO
ALTER TABLE [dbo].[QuoteFull_S]
    ADD CONSTRAINT [DF_QuoteFull_S_DiesCost] DEFAULT ((0)) FOR [DiesCost];


GO
PRINT N'Creating DF_QuoteFull_S_PackCost...';


GO
ALTER TABLE [dbo].[QuoteFull_S]
    ADD CONSTRAINT [DF_QuoteFull_S_PackCost] DEFAULT ((0)) FOR [PackCost];


GO
PRINT N'Creating DF_QuoteFull_S_TranspCost...';


GO
ALTER TABLE [dbo].[QuoteFull_S]
    ADD CONSTRAINT [DF_QuoteFull_S_TranspCost] DEFAULT ((0)) FOR [TranspCost];


GO
PRINT N'Creating DF_QuoteFull_S_SellCost01...';


GO
ALTER TABLE [dbo].[QuoteFull_S]
    ADD CONSTRAINT [DF_QuoteFull_S_SellCost01] DEFAULT ((0)) FOR [SellCost01];


GO
PRINT N'Creating DF_QuoteFull_S_RefCost01...';


GO
ALTER TABLE [dbo].[QuoteFull_S]
    ADD CONSTRAINT [DF_QuoteFull_S_RefCost01] DEFAULT ((0)) FOR [RefCost01];


GO
PRINT N'Creating DF_QuoteFull_S_SellCost04...';


GO
ALTER TABLE [dbo].[QuoteFull_S]
    ADD CONSTRAINT [DF_QuoteFull_S_SellCost04] DEFAULT ((0)) FOR [SellCost04];


GO
PRINT N'Creating DF_QuoteFull_S_RefCost04...';


GO
ALTER TABLE [dbo].[QuoteFull_S]
    ADD CONSTRAINT [DF_QuoteFull_S_RefCost04] DEFAULT ((0)) FOR [RefCost04];


GO
PRINT N'Creating DF_QuoteFull_S_WSR01_avg...';


GO
ALTER TABLE [dbo].[QuoteFull_S]
    ADD CONSTRAINT [DF_QuoteFull_S_WSR01_avg] DEFAULT ((0)) FOR [WSR01_sim];


GO
PRINT N'Creating DF_QuoteFull_S_WSR01...';


GO
ALTER TABLE [dbo].[QuoteFull_S]
    ADD CONSTRAINT [DF_QuoteFull_S_WSR01] DEFAULT ((0)) FOR [WSR01];


GO
PRINT N'Creating DF_QuoteFull_S_MSR01_avg...';


GO
ALTER TABLE [dbo].[QuoteFull_S]
    ADD CONSTRAINT [DF_QuoteFull_S_MSR01_avg] DEFAULT ((0)) FOR [MSR01_sim];


GO
PRINT N'Creating DF_QuoteFull_S_MSR01...';


GO
ALTER TABLE [dbo].[QuoteFull_S]
    ADD CONSTRAINT [DF_QuoteFull_S_MSR01] DEFAULT ((0)) FOR [MSR01];


GO
PRINT N'Creating DF_QuoteFull_S_NetProd01_avg...';


GO
ALTER TABLE [dbo].[QuoteFull_S]
    ADD CONSTRAINT [DF_QuoteFull_S_NetProd01_avg] DEFAULT ((0)) FOR [NetProd01_sim];


GO
PRINT N'Creating DF_QuoteFull_S_NetProd01_sim1...';


GO
ALTER TABLE [dbo].[QuoteFull_S]
    ADD CONSTRAINT [DF_QuoteFull_S_NetProd01_sim1] DEFAULT ((0)) FOR [NetProd04_sim];


GO
PRINT N'Creating DF_QuoteFull_S_NetProd01...';


GO
ALTER TABLE [dbo].[QuoteFull_S]
    ADD CONSTRAINT [DF_QuoteFull_S_NetProd01] DEFAULT ((0)) FOR [NetProd01];


GO
PRINT N'Creating DF_QuoteFull_S_FC4UG01...';


GO
ALTER TABLE [dbo].[QuoteFull_S]
    ADD CONSTRAINT [DF_QuoteFull_S_FC4UG01] DEFAULT ((0)) FOR [FC4UG01];


GO
PRINT N'Creating DF_QuoteFull_S_VC4UG01...';


GO
ALTER TABLE [dbo].[QuoteFull_S]
    ADD CONSTRAINT [DF_QuoteFull_S_VC4UG01] DEFAULT ((0)) FOR [VC4UG01];


GO
PRINT N'Creating DF_QuoteFull_S_OH4UG01...';


GO
ALTER TABLE [dbo].[QuoteFull_S]
    ADD CONSTRAINT [DF_QuoteFull_S_OH4UG01] DEFAULT ((0)) FOR [OH4UG01];


GO
PRINT N'Creating DF_QuoteFull_S_SC4UG01...';


GO
ALTER TABLE [dbo].[QuoteFull_S]
    ADD CONSTRAINT [DF_QuoteFull_S_SC4UG01] DEFAULT ((0)) FOR [SC4UG01];


GO
PRINT N'Creating DF_QuoteFull_S_DSR_avg...';


GO
ALTER TABLE [dbo].[QuoteFull_S]
    ADD CONSTRAINT [DF_QuoteFull_S_DSR_avg] DEFAULT ((0)) FOR [DSR_sim];


GO
PRINT N'Creating DF_QuoteFull_S_DSR...';


GO
ALTER TABLE [dbo].[QuoteFull_S]
    ADD CONSTRAINT [DF_QuoteFull_S_DSR] DEFAULT ((0)) FOR [DSR];


GO
PRINT N'Creating DF_QuoteFull_S_NetProd04...';


GO
ALTER TABLE [dbo].[QuoteFull_S]
    ADD CONSTRAINT [DF_QuoteFull_S_NetProd04] DEFAULT ((0)) FOR [NetProd04];


GO
PRINT N'Creating DF_QuoteFull_S_FC4UG04...';


GO
ALTER TABLE [dbo].[QuoteFull_S]
    ADD CONSTRAINT [DF_QuoteFull_S_FC4UG04] DEFAULT ((0)) FOR [FC4UG04];


GO
PRINT N'Creating DF_QuoteFull_S_VC4UG04...';


GO
ALTER TABLE [dbo].[QuoteFull_S]
    ADD CONSTRAINT [DF_QuoteFull_S_VC4UG04] DEFAULT ((0)) FOR [VC4UG04];


GO
PRINT N'Creating DF_QuoteFull_S_FVC...';


GO
ALTER TABLE [dbo].[QuoteFull_S]
    ADD CONSTRAINT [DF_QuoteFull_S_FVC] DEFAULT ((0)) FOR [FVC];


GO
PRINT N'Creating DF_QuoteFull_S_Charge...';


GO
ALTER TABLE [dbo].[QuoteFull_S]
    ADD CONSTRAINT [DF_QuoteFull_S_Charge] DEFAULT ((0)) FOR [Charge];


GO
PRINT N'Creating DF_ProductionLogRaw_NrPos_KO...';


GO
ALTER TABLE [tmp].[ProductionLogRaw_KO]
    ADD CONSTRAINT [DF_ProductionLogRaw_NrPos_KO] DEFAULT ('') FOR [NrPos];


GO
PRINT N'Creating DF_ProductionLogRaw_KO_okPr...';


GO
ALTER TABLE [tmp].[ProductionLogRaw_KO]
    ADD CONSTRAINT [DF_ProductionLogRaw_KO_okPr] DEFAULT ((1)) FOR [okPr];


GO
PRINT N'Creating DF_ProductionLogRaw_KO_okQM...';


GO
ALTER TABLE [tmp].[ProductionLogRaw_KO]
    ADD CONSTRAINT [DF_ProductionLogRaw_KO_okQM] DEFAULT ((1)) FOR [okQM];


GO
PRINT N'Creating DF_ProductionLogRaw_KO_okSc...';


GO
ALTER TABLE [tmp].[ProductionLogRaw_KO]
    ADD CONSTRAINT [DF_ProductionLogRaw_KO_okSc] DEFAULT ((1)) FOR [okSc];


GO
PRINT N'Creating DF_ProductionLogRaw_KO_okDi...';


GO
ALTER TABLE [tmp].[ProductionLogRaw_KO]
    ADD CONSTRAINT [DF_ProductionLogRaw_KO_okDi] DEFAULT ((1)) FOR [okDi];


GO
PRINT N'Creating DF_ProductionLogRaw_KO_ImportDate...';


GO
ALTER TABLE [tmp].[ProductionLogRaw_KO]
    ADD CONSTRAINT [DF_ProductionLogRaw_KO_ImportDate] DEFAULT (getdate()) FOR [ImportDate];


GO
PRINT N'Creating DF_ClientsRaw_TranspZone...';


GO
ALTER TABLE [tmp].[ClientsRaw]
    ADD CONSTRAINT [DF_ClientsRaw_TranspZone] DEFAULT ('') FOR [TranspZone];


GO
PRINT N'Creating DF_ItemsRaw_Class01...';


GO
ALTER TABLE [tmp].[ItemsRaw]
    ADD CONSTRAINT [DF_ItemsRaw_Class01] DEFAULT ('') FOR [Class01];


GO
PRINT N'Creating DF_ItemsRaw_Class02...';


GO
ALTER TABLE [tmp].[ItemsRaw]
    ADD CONSTRAINT [DF_ItemsRaw_Class02] DEFAULT ('') FOR [Class02];


GO
PRINT N'Creating DF_ItemsRaw_Class03...';


GO
ALTER TABLE [tmp].[ItemsRaw]
    ADD CONSTRAINT [DF_ItemsRaw_Class03] DEFAULT ('') FOR [Class03];


GO
PRINT N'Creating DF_ItemsRaw_Class04...';


GO
ALTER TABLE [tmp].[ItemsRaw]
    ADD CONSTRAINT [DF_ItemsRaw_Class04] DEFAULT ('') FOR [Class04];


GO
PRINT N'Creating DF_ItemsRaw_Class05...';


GO
ALTER TABLE [tmp].[ItemsRaw]
    ADD CONSTRAINT [DF_ItemsRaw_Class05] DEFAULT ('') FOR [Class05];


GO
PRINT N'Creating DF_TraspZoneRaw...';


GO
ALTER TABLE [tmp].[TranspCostRaw]
    ADD CONSTRAINT [DF_TraspZoneRaw] DEFAULT ('') FOR [TranspZone];


GO
PRINT N'Creating DF_ProductionLogRaw_NrPos...';


GO
ALTER TABLE [tmp].[ProductionLogRaw]
    ADD CONSTRAINT [DF_ProductionLogRaw_NrPos] DEFAULT ('') FOR [NrPos];


GO
PRINT N'Creating DF_ProductionLogRaw_okPr...';


GO
ALTER TABLE [tmp].[ProductionLogRaw]
    ADD CONSTRAINT [DF_ProductionLogRaw_okPr] DEFAULT ((1)) FOR [okPr];


GO
PRINT N'Creating DF_ProductionLogRaw_okQM...';


GO
ALTER TABLE [tmp].[ProductionLogRaw]
    ADD CONSTRAINT [DF_ProductionLogRaw_okQM] DEFAULT ((1)) FOR [okQM];


GO
PRINT N'Creating DF_ProductionLogRaw_okSc...';


GO
ALTER TABLE [tmp].[ProductionLogRaw]
    ADD CONSTRAINT [DF_ProductionLogRaw_okSc] DEFAULT ((1)) FOR [okSc];


GO
PRINT N'Creating DF_ProductionLogRaw_okDi...';


GO
ALTER TABLE [tmp].[ProductionLogRaw]
    ADD CONSTRAINT [DF_ProductionLogRaw_okDi] DEFAULT ((1)) FOR [okDi];


GO
PRINT N'Creating DF_OrdersHistRaw_ProvCost...';


GO
ALTER TABLE [tmp].[OrdersHistRaw]
    ADD CONSTRAINT [DF_OrdersHistRaw_ProvCost] DEFAULT ((0)) FOR [ProvvCost];


GO
PRINT N'Creating DF_TraspZoneExt...';


GO
ALTER TABLE [ext].[TranspCostRaw]
    ADD CONSTRAINT [DF_TraspZoneExt] DEFAULT ('') FOR [TranspZone];


GO
PRINT N'Creating DF_ClientsRaw_ClassZona...';


GO
ALTER TABLE [ext].[ClientsRaw]
    ADD CONSTRAINT [DF_ClientsRaw_ClassZona] DEFAULT ('') FOR [TranspZone];


GO
PRINT N'Creating DF_ProductionLogRaw_NrPos_1...';


GO
ALTER TABLE [ext].[ProductionLogRaw]
    ADD CONSTRAINT [DF_ProductionLogRaw_NrPos_1] DEFAULT ('') FOR [NrPos];


GO
PRINT N'Creating DF_ProductionLogRaw_CodDies...';


GO
ALTER TABLE [ext].[ProductionLogRaw]
    ADD CONSTRAINT [DF_ProductionLogRaw_CodDies] DEFAULT ('') FOR [CodDies];


GO
PRINT N'Creating DF_ProductionLogRaw_CodClient...';


GO
ALTER TABLE [ext].[ProductionLogRaw]
    ADD CONSTRAINT [DF_ProductionLogRaw_CodClient] DEFAULT ('') FOR [CodClient];


GO
PRINT N'Creating DF_ProductionLogRaw_OrderNum...';


GO
ALTER TABLE [ext].[ProductionLogRaw]
    ADD CONSTRAINT [DF_ProductionLogRaw_OrderNum] DEFAULT ('') FOR [OrderNum];


GO
PRINT N'Creating DF_ProductionLogRaw_BatchNum...';


GO
ALTER TABLE [ext].[ProductionLogRaw]
    ADD CONSTRAINT [DF_ProductionLogRaw_BatchNum] DEFAULT ('') FOR [BatchNum];


GO
PRINT N'Creating DF_ProductionLogRaw_ProcessType...';


GO
ALTER TABLE [ext].[ProductionLogRaw]
    ADD CONSTRAINT [DF_ProductionLogRaw_ProcessType] DEFAULT ('') FOR [ProcessType];


GO
PRINT N'Creating DF_ProductionLogRaw_EventType...';


GO
ALTER TABLE [ext].[ProductionLogRaw]
    ADD CONSTRAINT [DF_ProductionLogRaw_EventType] DEFAULT ('') FOR [EventType];


GO
PRINT N'Creating DF_ProductionLogRaw_RawMat...';


GO
ALTER TABLE [ext].[ProductionLogRaw]
    ADD CONSTRAINT [DF_ProductionLogRaw_RawMat] DEFAULT ('') FOR [RawMat];


GO
PRINT N'Creating DF_ProductionLogRaw_CodPackag...';


GO
ALTER TABLE [ext].[ProductionLogRaw]
    ADD CONSTRAINT [DF_ProductionLogRaw_CodPackag] DEFAULT ('') FOR [CodPackag];


GO
PRINT N'Creating DF_ProductionLogRaw_QtyIN...';


GO
ALTER TABLE [ext].[ProductionLogRaw]
    ADD CONSTRAINT [DF_ProductionLogRaw_QtyIN] DEFAULT ((0)) FOR [QtyIN];


GO
PRINT N'Creating DF_ProductionLogRaw_QtyOUT...';


GO
ALTER TABLE [ext].[ProductionLogRaw]
    ADD CONSTRAINT [DF_ProductionLogRaw_QtyOUT] DEFAULT ((0)) FOR [QtyOUT];


GO
PRINT N'Creating DF_ProductionLogRaw_QtyEXT...';


GO
ALTER TABLE [ext].[ProductionLogRaw]
    ADD CONSTRAINT [DF_ProductionLogRaw_QtyEXT] DEFAULT ((0)) FOR [QtyEXT];


GO
PRINT N'Creating DF_ProductionLogRaw_NumIN...';


GO
ALTER TABLE [ext].[ProductionLogRaw]
    ADD CONSTRAINT [DF_ProductionLogRaw_NumIN] DEFAULT ((0)) FOR [NumIN];


GO
PRINT N'Creating DF_ProductionLogRaw_NumOUT...';


GO
ALTER TABLE [ext].[ProductionLogRaw]
    ADD CONSTRAINT [DF_ProductionLogRaw_NumOUT] DEFAULT ((0)) FOR [NumOUT];


GO
PRINT N'Creating DF_ProductionLogRaw_QuotaPlant...';


GO
ALTER TABLE [ext].[ProductionLogRaw]
    ADD CONSTRAINT [DF_ProductionLogRaw_QuotaPlant] DEFAULT ((0)) FOR [QuotaPlant];


GO
PRINT N'Creating DF_ProductionLogRaw_QuotaMan...';


GO
ALTER TABLE [ext].[ProductionLogRaw]
    ADD CONSTRAINT [DF_ProductionLogRaw_QuotaMan] DEFAULT ((0)) FOR [QuotaMan];


GO
PRINT N'Creating DF_ProductionLogRaw_Tags...';


GO
ALTER TABLE [ext].[ProductionLogRaw]
    ADD CONSTRAINT [DF_ProductionLogRaw_Tags] DEFAULT ('') FOR [Tags];


GO
PRINT N'Creating DF_ProductionLogRaw_okPr_1...';


GO
ALTER TABLE [ext].[ProductionLogRaw]
    ADD CONSTRAINT [DF_ProductionLogRaw_okPr_1] DEFAULT ((1)) FOR [okPr];


GO
PRINT N'Creating DF_ProductionLogRaw_okQM_1...';


GO
ALTER TABLE [ext].[ProductionLogRaw]
    ADD CONSTRAINT [DF_ProductionLogRaw_okQM_1] DEFAULT ((1)) FOR [okQM];


GO
PRINT N'Creating DF_ProductionLogRaw_okSc_1...';


GO
ALTER TABLE [ext].[ProductionLogRaw]
    ADD CONSTRAINT [DF_ProductionLogRaw_okSc_1] DEFAULT ((1)) FOR [okSc];


GO
PRINT N'Creating DF_ProductionLogRaw_okDi_1...';


GO
ALTER TABLE [ext].[ProductionLogRaw]
    ADD CONSTRAINT [DF_ProductionLogRaw_okDi_1] DEFAULT ((1)) FOR [okDi];


GO
PRINT N'Creating DF_ProductionLogRaw_KO_okPr...';


GO
ALTER TABLE [ext].[ProductionLogRaw_KO]
    ADD CONSTRAINT [DF_ProductionLogRaw_KO_okPr] DEFAULT ((1)) FOR [okPr];


GO
PRINT N'Creating DF_ProductionLogRaw_KO_okQM...';


GO
ALTER TABLE [ext].[ProductionLogRaw_KO]
    ADD CONSTRAINT [DF_ProductionLogRaw_KO_okQM] DEFAULT ((1)) FOR [okQM];


GO
PRINT N'Creating DF_ProductionLogRaw_KO_okSc...';


GO
ALTER TABLE [ext].[ProductionLogRaw_KO]
    ADD CONSTRAINT [DF_ProductionLogRaw_KO_okSc] DEFAULT ((1)) FOR [okSc];


GO
PRINT N'Creating DF_ProductionLogRaw_KO_okDi...';


GO
ALTER TABLE [ext].[ProductionLogRaw_KO]
    ADD CONSTRAINT [DF_ProductionLogRaw_KO_okDi] DEFAULT ((1)) FOR [okDi];


GO
PRINT N'Creating DF_ProductionLogRaw_KO_ImportDateExt...';


GO
ALTER TABLE [ext].[ProductionLogRaw_KO]
    ADD CONSTRAINT [DF_ProductionLogRaw_KO_ImportDateExt] DEFAULT (getdate()) FOR [ImportDateExt];


GO
PRINT N'Creating DF_ItemsRaw_CodPlant...';


GO
ALTER TABLE [ext].[ItemsRaw]
    ADD CONSTRAINT [DF_ItemsRaw_CodPlant] DEFAULT ('') FOR [CodPlant];


GO
PRINT N'Creating DF_ItemsRaw_Class01_1...';


GO
ALTER TABLE [ext].[ItemsRaw]
    ADD CONSTRAINT [DF_ItemsRaw_Class01_1] DEFAULT ('') FOR [Class01];


GO
PRINT N'Creating DF_ItemsRaw_Class02_1...';


GO
ALTER TABLE [ext].[ItemsRaw]
    ADD CONSTRAINT [DF_ItemsRaw_Class02_1] DEFAULT ('') FOR [Class02];


GO
PRINT N'Creating DF_ItemsRaw_Class03_1...';


GO
ALTER TABLE [ext].[ItemsRaw]
    ADD CONSTRAINT [DF_ItemsRaw_Class03_1] DEFAULT ('') FOR [Class03];


GO
PRINT N'Creating DF_ItemsRaw_Class04_1...';


GO
ALTER TABLE [ext].[ItemsRaw]
    ADD CONSTRAINT [DF_ItemsRaw_Class04_1] DEFAULT ('') FOR [Class04];


GO
PRINT N'Creating DF_ItemsRaw_Class05_1...';


GO
ALTER TABLE [ext].[ItemsRaw]
    ADD CONSTRAINT [DF_ItemsRaw_Class05_1] DEFAULT ('') FOR [Class05];


GO
PRINT N'Creating DF_OrdersHistRaw_OrdNum...';


GO
ALTER TABLE [ext].[OrdersHistRaw]
    ADD CONSTRAINT [DF_OrdersHistRaw_OrdNum] DEFAULT ((0)) FOR [OrdNum];


GO
PRINT N'Creating DF_OrdersHistRaw_OrdRow...';


GO
ALTER TABLE [ext].[OrdersHistRaw]
    ADD CONSTRAINT [DF_OrdersHistRaw_OrdRow] DEFAULT ((0)) FOR [OrdRow];


GO
PRINT N'Creating DF_OrdersHistRaw_OrdDate...';


GO
ALTER TABLE [ext].[OrdersHistRaw]
    ADD CONSTRAINT [DF_OrdersHistRaw_OrdDate] DEFAULT (getdate()) FOR [OrdDate];


GO
PRINT N'Creating DF_OrdersHistRaw_CodItem...';


GO
ALTER TABLE [ext].[OrdersHistRaw]
    ADD CONSTRAINT [DF_OrdersHistRaw_CodItem] DEFAULT ('') FOR [CodItem];


GO
PRINT N'Creating DF_OrdersHistRaw_RawMatCost...';


GO
ALTER TABLE [ext].[OrdersHistRaw]
    ADD CONSTRAINT [DF_OrdersHistRaw_RawMatCost] DEFAULT ((0)) FOR [RawMatCost];


GO
PRINT N'Creating DF_OrdersHistRaw_BatchQty...';


GO
ALTER TABLE [ext].[OrdersHistRaw]
    ADD CONSTRAINT [DF_OrdersHistRaw_BatchQty] DEFAULT ((0)) FOR [BatchQty];


GO
PRINT N'Creating DF_OrdersHistRaw_OrdPrice...';


GO
ALTER TABLE [ext].[OrdersHistRaw]
    ADD CONSTRAINT [DF_OrdersHistRaw_OrdPrice] DEFAULT ((0)) FOR [OrdPrice];


GO
PRINT N'Creating DF_OrdersHistRaw_RawMatExtraCost...';


GO
ALTER TABLE [ext].[OrdersHistRaw]
    ADD CONSTRAINT [DF_OrdersHistRaw_RawMatExtraCost] DEFAULT ((0)) FOR [RawMatExtraCost];


GO
PRINT N'Creating DF_OrdersHistRaw_PriceOff...';


GO
ALTER TABLE [ext].[OrdersHistRaw]
    ADD CONSTRAINT [DF_OrdersHistRaw_PriceOff] DEFAULT ((0)) FOR [PriceOff];


GO
PRINT N'Creating DF_OrdersHistRaw_OrderQty...';


GO
ALTER TABLE [ext].[OrdersHistRaw]
    ADD CONSTRAINT [DF_OrdersHistRaw_OrderQty] DEFAULT ((0)) FOR [OrdQty];


GO
PRINT N'Creating DF_OrdersHistRaw_ProvvCost...';


GO
ALTER TABLE [ext].[OrdersHistRaw]
    ADD CONSTRAINT [DF_OrdersHistRaw_ProvvCost] DEFAULT ((0)) FOR [ProvvCost];


GO
PRINT N'Creating DF_RcdItem_ItemDescrRcd...';


GO
ALTER TABLE [ext].[RcdItem]
    ADD CONSTRAINT [DF_RcdItem_ItemDescrRcd] DEFAULT ('') FOR [ItemDescrRcd];


GO
PRINT N'Creating DF_RcdItem_CodPlantRcd...';


GO
ALTER TABLE [ext].[RcdItem]
    ADD CONSTRAINT [DF_RcdItem_CodPlantRcd] DEFAULT ('') FOR [CodPlantRcd];


GO
PRINT N'Creating DF_RcdClient_ClientNameRcd...';


GO
ALTER TABLE [ext].[RcdClient]
    ADD CONSTRAINT [DF_RcdClient_ClientNameRcd] DEFAULT ('') FOR [ClientNameRcd];


GO
PRINT N'Creating DF_RcdClass_CodClassRcd...';


GO
ALTER TABLE [ext].[RcdClass01]
    ADD CONSTRAINT [DF_RcdClass_CodClassRcd] DEFAULT ('') FOR [CodClass01Rcd];


GO
PRINT N'Creating DF_RcdPackage_PackagDescOrig...';


GO
ALTER TABLE [ext].[RcdPackage]
    ADD CONSTRAINT [DF_RcdPackage_PackagDescOrig] DEFAULT ('') FOR [PackagDesc];


GO
PRINT N'Creating FK_Vocabolario_Lingue...';


GO
ALTER TABLE [dbo].[Vocabolario]
    ADD CONSTRAINT [FK_Vocabolario_Lingue] FOREIGN KEY ([Lingua]) REFERENCES [dbo].[Lingue] ([Lingua]) ON UPDATE CASCADE;


GO
PRINT N'Creating FK_QuoteExtra_QuoteList...';


GO
ALTER TABLE [dbo].[QuoteOC]
    ADD CONSTRAINT [FK_QuoteExtra_QuoteList] FOREIGN KEY ([QuoteType], [CodQuote], [QuoteRev]) REFERENCES [dbo].[QuoteList] ([QuoteType], [CodQuote], [QuoteRev]) ON UPDATE CASCADE;


GO
PRINT N'Creating FK_QuoteWorkExt_QuoteList...';


GO
ALTER TABLE [dbo].[QuoteWorkExt]
    ADD CONSTRAINT [FK_QuoteWorkExt_QuoteList] FOREIGN KEY ([QuoteType], [CodQuote], [QuoteRev]) REFERENCES [dbo].[QuoteList] ([QuoteType], [CodQuote], [QuoteRev]) ON UPDATE CASCADE;


GO
PRINT N'Creating FK_Package2Item_ItemDet...';


GO
ALTER TABLE [dbo].[Package2Item]
    ADD CONSTRAINT [FK_Package2Item_ItemDet] FOREIGN KEY ([CodItem]) REFERENCES [dbo].[ItemDet] ([CodItem]) ON UPDATE CASCADE;


GO
PRINT N'Creating FK_Package2Item_PackagDet...';


GO
ALTER TABLE [dbo].[Package2Item]
    ADD CONSTRAINT [FK_Package2Item_PackagDet] FOREIGN KEY ([CodPackag]) REFERENCES [dbo].[PackagDet] ([CodPackag]) ON UPDATE CASCADE;


GO
PRINT N'Creating FK_Package2ItemClient_ClientDet...';


GO
ALTER TABLE [dbo].[Package2ItemClient]
    ADD CONSTRAINT [FK_Package2ItemClient_ClientDet] FOREIGN KEY ([CodClient]) REFERENCES [dbo].[ClientDet] ([CodClient]) ON UPDATE CASCADE;


GO
PRINT N'Creating FK_Package2ItemClient_ItemDet...';


GO
ALTER TABLE [dbo].[Package2ItemClient]
    ADD CONSTRAINT [FK_Package2ItemClient_ItemDet] FOREIGN KEY ([CodItem]) REFERENCES [dbo].[ItemDet] ([CodItem]) ON UPDATE CASCADE;


GO
PRINT N'Creating FK_Package2ItemClient_PackagDet...';


GO
ALTER TABLE [dbo].[Package2ItemClient]
    ADD CONSTRAINT [FK_Package2ItemClient_PackagDet] FOREIGN KEY ([CodPackag]) REFERENCES [dbo].[PackagDet] ([CodPackag]) ON UPDATE CASCADE;


GO
PRINT N'Creating FK_Cost2Plant_PlantsDet...';


GO
ALTER TABLE [dbo].[Cost2Plant]
    ADD CONSTRAINT [FK_Cost2Plant_PlantsDet] FOREIGN KEY ([CodPlant]) REFERENCES [dbo].[PlantsDet] ([CodPlant]) ON UPDATE CASCADE;


GO
PRINT N'Creating FK_ClientDet_AgentsDet...';


GO
ALTER TABLE [dbo].[ClientDet]
    ADD CONSTRAINT [FK_ClientDet_AgentsDet] FOREIGN KEY ([CodAg]) REFERENCES [dbo].[AgentsDet] ([CodAg]) ON UPDATE CASCADE;


GO
PRINT N'Creating FK_QuoteRM_QuoteList...';


GO
ALTER TABLE [dbo].[QuoteRM]
    ADD CONSTRAINT [FK_QuoteRM_QuoteList] FOREIGN KEY ([QuoteType], [CodQuote], [QuoteRev]) REFERENCES [dbo].[QuoteList] ([QuoteType], [CodQuote], [QuoteRev]) ON UPDATE CASCADE;


GO
PRINT N'Creating FK_Package2_PackagDet...';


GO
ALTER TABLE [dbo].[Package2]
    ADD CONSTRAINT [FK_Package2_PackagDet] FOREIGN KEY ([CodPackag]) REFERENCES [dbo].[PackagDet] ([CodPackag]) ON UPDATE CASCADE;


GO
PRINT N'Creating FK_Permessi2Funzione_Permessi...';


GO
ALTER TABLE [dbo].[Permessi2Funzione]
    ADD CONSTRAINT [FK_Permessi2Funzione_Permessi] FOREIGN KEY ([COD_PERMESSO]) REFERENCES [dbo].[Permessi] ([COD_PERMESSO]) ON UPDATE CASCADE;


GO
PRINT N'Creating FK_DiesDet_DiesGroupDet...';


GO
ALTER TABLE [dbo].[DiesDet]
    ADD CONSTRAINT [FK_DiesDet_DiesGroupDet] FOREIGN KEY ([CodDiesGroup]) REFERENCES [dbo].[DiesGroupDet] ([CodDiesGroup]) ON UPDATE CASCADE;


GO
PRINT N'Creating FK_DiesDet_ItemDet...';


GO
ALTER TABLE [dbo].[DiesDet]
    ADD CONSTRAINT [FK_DiesDet_ItemDet] FOREIGN KEY ([CodItem]) REFERENCES [dbo].[ItemDet] ([CodItem]) ON UPDATE CASCADE;


GO
PRINT N'Creating FK_ProductionLog_ClientDet...';


GO
ALTER TABLE [dbo].[ProductionLog]
    ADD CONSTRAINT [FK_ProductionLog_ClientDet] FOREIGN KEY ([CodClient]) REFERENCES [dbo].[ClientDet] ([CodClient]) ON UPDATE CASCADE;


GO
PRINT N'Creating FK_ProductionLog_PackagDet...';


GO
ALTER TABLE [dbo].[ProductionLog]
    ADD CONSTRAINT [FK_ProductionLog_PackagDet] FOREIGN KEY ([CodPackag]) REFERENCES [dbo].[PackagDet] ([CodPackag]) ON UPDATE CASCADE;


GO
PRINT N'Creating FK_ProductionLog_PlantsDet...';


GO
ALTER TABLE [dbo].[ProductionLog]
    ADD CONSTRAINT [FK_ProductionLog_PlantsDet] FOREIGN KEY ([CodPlant]) REFERENCES [dbo].[PlantsDet] ([CodPlant]) ON UPDATE CASCADE;


GO
PRINT N'Creating FK_ProductionLog_RawMatDet...';


GO
ALTER TABLE [dbo].[ProductionLog]
    ADD CONSTRAINT [FK_ProductionLog_RawMatDet] FOREIGN KEY ([RawMat]) REFERENCES [dbo].[RawMatDet] ([RawMat]) ON UPDATE CASCADE;


GO
PRINT N'Creating FK_QuoteParam_QuoteList...';


GO
ALTER TABLE [dbo].[QuoteParam]
    ADD CONSTRAINT [FK_QuoteParam_QuoteList] FOREIGN KEY ([QuoteType], [CodQuote], [QuoteRev]) REFERENCES [dbo].[QuoteList] ([QuoteType], [CodQuote], [QuoteRev]) ON UPDATE CASCADE;


GO
PRINT N'Creating FK_QuoteWorkInt_QuoteList...';


GO
ALTER TABLE [dbo].[QuoteWorkInt]
    ADD CONSTRAINT [FK_QuoteWorkInt_QuoteList] FOREIGN KEY ([QuoteType], [CodQuote], [QuoteRev]) REFERENCES [dbo].[QuoteList] ([QuoteType], [CodQuote], [QuoteRev]) ON UPDATE CASCADE;


GO
PRINT N'Creating FK_UTENTE_CDC...';


GO
ALTER TABLE [dbo].[UTENTE]
    ADD CONSTRAINT [FK_UTENTE_CDC] FOREIGN KEY ([COD_CDC]) REFERENCES [dbo].[CDC] ([COD_CDC]) ON UPDATE CASCADE;


GO
PRINT N'Creating FK_DIRITTI_FUNZIONE...';


GO
ALTER TABLE [dbo].[DIRITTI]
    ADD CONSTRAINT [FK_DIRITTI_FUNZIONE] FOREIGN KEY ([COD_FUNZIONE]) REFERENCES [dbo].[FUNZIONE] ([COD_FUNZIONE]) ON UPDATE CASCADE;


GO
PRINT N'Creating FK_DIRITTI_MODULO...';


GO
ALTER TABLE [dbo].[DIRITTI]
    ADD CONSTRAINT [FK_DIRITTI_MODULO] FOREIGN KEY ([COD_MODULO]) REFERENCES [dbo].[MODULO] ([COD_MODULO]) ON UPDATE CASCADE;


GO
PRINT N'Creating FK_DIRITTI_UTENTE...';


GO
ALTER TABLE [dbo].[DIRITTI]
    ADD CONSTRAINT [FK_DIRITTI_UTENTE] FOREIGN KEY ([USER_NAME]) REFERENCES [dbo].[UTENTE] ([USER_NAME]) ON UPDATE CASCADE;


GO
PRINT N'Creating [dbo].[f_dtFromRaw]...';


GO
-- =============================================
-- Author:		S.E.Locatelli
-- Create date: 2013.11.28
-- Description:	Conversione datetime da yyyyMMddHHmmssnn
-- =============================================
CREATE FUNCTION f_dtFromRaw 
(
	-- Add the parameters for the function here
	@origDt nvarchar(50)
)
RETURNS datetime
AS
BEGIN
	DECLARE @output datetime
	DECLARE @strDt NVARCHAR(50)

	SELECT	@strDt = LEFT(@origDt, 4) + '-' + SUBSTRING(@origDt, 5,2 ) + '-' + SUBSTRING(@origDt, 7,2 ) + ' ' + SUBSTRING(@origDt, 9,2 ) + ':' + SUBSTRING(@origDt, 11,2 ) + ':' + SUBSTRING(@origDt, 13,2 ) + '.' + SUBSTRING(@origDt, 15,2 ) +'0'

	SELECT	@output = CONVERT(DATETIME, @strDt, 121)

	RETURN @output

END
GO
PRINT N'Creating [dbo].[f_trim]...';


GO
/***************************************
* FUNCTION f_trim
*
* trim completo: LTRIM(RTRIM(...))
*
* Steamware, S.E.L.
* mod: 2013.05.10
*
****************************************/
create FUNCTION [dbo].[f_trim] (@string NVARCHAR(MAX))
RETURNS NVARCHAR(MAX) AS  
BEGIN

 -- Prefix the required number of spaces to bulk up the string and then replace the spaces with the desired character
 RETURN LTRIM(RTRIM(@string))
        

END
GO
PRINT N'Creating [dbo].[f_getCodPackag_OLD]...';


GO


-- =============================================
-- Author:		S.E.Locatelli
-- Create date: 2014.01.15
-- Description:	Recupera CodPackage dato CodItem e CodClient secondo albero decisionale
--              SOSTITUITA da fun Table-value f_getDataCodPackag in QL_Update
-- =============================================
CREATE FUNCTION [dbo].[f_getCodPackag_OLD] 
(
	@CodItem	NVARCHAR(50),
	@CodClient	NVARCHAR(50)
)
RETURNS NVARCHAR(50)
AS
BEGIN
	DECLARE @output NVARCHAR(50)
	DECLARE @trovati INT = 0
	-- setup iniziale: imposto a zero...
	SET		@output = '0'

	SELECT	@trovati = COUNT(*) FROM Package2ItemClient WHERE CodClient = @CodClient AND CodItem = @CodItem
	IF(@trovati > 0)
		-- primo tentativo: cerco il package dato SIA cliente che ITEM
		BEGIN
			SELECT	TOP 1	@output = CodPackag
			FROM			Package2ItemClient WHERE CodClient = @CodClient AND CodItem = @CodItem
			ORDER BY		TotQta DESC
		END
	ELSE
		-- secondo tentativo: se non lo trovo cerco per SOLO ITEM
		BEGIN
			SELECT	TOP 1	@output = CodPackag
			FROM			Package2Item WHERE CodItem = @CodItem
			ORDER BY		TotQta DESC
		END
	
	RETURN @output

END
GO
PRINT N'Creating [dbo].[f_padLeft]...';


GO

/***************************************
* FUNCTION f_padLeft
*
* fornisce una stringa della lunghezza desiderata aggiungendo a sx il carattere richiesto alla @string originale
*
* Steamware, S.E.L.
* mod: 2010.03.19
*
****************************************/
CREATE FUNCTION [dbo].[f_padLeft] (@string VARCHAR(255), @desired_length INTEGER, @pad_character CHAR(1))
RETURNS VARCHAR(255) AS  
BEGIN

 -- Prefix the required number of spaces to bulk up the string and then replace the spaces with the desired character
 RETURN CASE
          WHEN LEN(@string) < @desired_length
            THEN REPLACE(SPACE(@desired_length - LEN(@string)), ' ', @pad_character) + @string
          ELSE @string
        END

END
GO
PRINT N'Creating [dbo].[f_padRight]...';


GO
/***************************************
* FUNCTION f_padRight
*
* fornisce una stringa della lunghezza desiderata aggiungendo a sx il carattere richiesto alla @string originale
*
* Steamware, S.E.L.
* mod: 2010.03.19
*
****************************************/
CREATE FUNCTION [dbo].[f_padRight] (@string VARCHAR(255), @desired_length INTEGER, @pad_character CHAR(1))
RETURNS VARCHAR(255) AS  
BEGIN

 -- Prefix the required number of spaces to bulk up the string and then replace the spaces with the desired character
 RETURN CASE
          WHEN LEN(@string) < @desired_length
            THEN @string + REPLACE(SPACE(@desired_length - LEN(@string)), ' ', @pad_character)
          ELSE @string
        END

END
GO
PRINT N'Creating [dbo].[f_getSubstring]...';


GO
-- ================================================================
-- Author     : Steamware
-- Create date: 2014-01-17
--
-- Description:	Data una stringa con una serie di valori separati da un separatore ( es. ; )
--              ritorna l'elemento nella posizione richiesta
--
-- esempio    : SELECT dbo.f_GetSubstring('asda-fff-bbb','-' , 2)
-- ================================================================
CREATE FUNCTION [dbo].[f_getSubstring]
( 
    @str_in NVARCHAR(4000), @separator NVARCHAR(4)= '-', @PosizValue INT = 1
)
RETURNS NVARCHAR(4000)
AS
BEGIN

    DECLARE	@Occurrences	INT,
            @Counter	    INT,
            @tmpStr	        NVARCHAR(4000),
            @str_out        NVARCHAR(4000)

    IF RIGHT(@str_in, DATALENGTH(@separator)/2 ) <> @separator
        SET @str_out = @str_in + @separator ;
    ELSE 
        SET @str_out = @str_in ;

    -- calcolo il numero di elementi della nella stringa
    SET @Occurrences = ( (DATALENGTH( REPLACE(@str_out, @separator, @separator+'#')) -  DATALENGTH(@str_out)) ) / 2

    -- se l'elemento richiesto esiste proseguo altrimenti ritorno NULL
    IF @Occurrences >= @PosizValue AND @PosizValue <> 0
     BEGIN 

        SET @tmpStr = @str_out ;
        SET @Counter = 1 ;

        WHILE @Counter <= @PosizValue
         BEGIN
            SET @Counter = @Counter + 1 ;
            SET @str_out = SUBSTRING( @tmpStr, 1, CHARINDEX(@separator,@tmpStr) - 1) ;
            -- metto via il resto della stringa
            SET @tmpStr  = SUBSTRING( @tmpStr, CHARINDEX(@separator,@tmpStr) + DATALENGTH(@separator)/2, 4000) ;
            
            IF DATALENGTH(@tmpStr) = 0
                BREAK
         END

        -- pulisco da caratteri NON voluti
        --SET @str_out = REPLACE(@str_out, char(13), '')    ; -- carriage return
        --SET @str_out = REPLACE(@str_out, char(10), '')    ; -- line feed
        --SET @str_out = REPLACE(@str_out, char(9), '')     ; -- tab
        --SET @str_out = LTRIM ( RTRIM (@str_out) )         ; -- blank
     END
    ELSE 
        SET @str_out = NULL ;

  RETURN @str_out

END
GO
PRINT N'Creating [dbo].[f_getNewCodQuote]...';


GO
-- =============================================
-- Author:		S.E.Locatelli
-- Create date: 2014.02.21
-- Description:	Retituisce un codice offerta valido da yyMMdd + incr
-- =============================================
CREATE FUNCTION [dbo].[f_getNewCodQuote]
(
)
RETURNS INT
AS
BEGIN

	DECLARE @output INT
	DECLARE @oggi DATETIME = GETDATE()
	
	
	SELECT @output = ISNULL(MAX(CodQuote) + 1,CAST(RIGHT(YEAR(@oggi),2) AS NVARCHAR) + dbo.f_padLeft(MONTH(@oggi), 2,'0') + dbo.f_padLeft(DAY(@oggi), 2,'0')+'0001')
	FROM QuoteList
	WHERE codquote LIKE CAST(RIGHT(YEAR(@oggi),2) AS NVARCHAR) + dbo.f_padLeft(MONTH(@oggi), 2,'0') + dbo.f_padLeft(DAY(@oggi), 2,'0') + '%'
    AND (QuoteType = 'Q' OR QuoteType = 'S') 

	RETURN @output

	/* altra modalità (valutare...)
	-- calcolo prox valori "free" x cod Quote (QuoteRev parte a zero...)
	SELECT	@CodQuote = ISNULL(CodQuote, 0)
	FROM QuoteList
	WHERE QuoteType = 'Q'
	AND CodQuote LIKE dbo.fnFormatDate (getdate(), 'YYMMDD') +'%'

	-- se è vuoto prendo primo valore...
	IF(@CodQuote = 0)
	BEGIN
		SELECT @CodQuote = dbo.fnFormatDate (getdate(), 'YYMMDD0000') 
	END


	*/


END
GO
PRINT N'Creating [dbo].[fnFormatDate]...';


GO
-----------------------------------------------------------------------------
-- SQL Server date formatting function – convert datetime to string
-----------------------------------------------------------------------------
-- SQL datetime functions
-- SQL Server date formats
-- T-SQL convert dates
-- Formatting dates sql server
CREATE FUNCTION dbo.fnFormatDate (@Datetime DATETIME, @FormatMask VARCHAR(32))
RETURNS VARCHAR(32)
AS
BEGIN
    DECLARE @StringDate VARCHAR(32)
    SET @StringDate = @FormatMask
    IF (CHARINDEX ('YYYY',@StringDate) > 0)
       SET @StringDate = REPLACE(@StringDate, 'YYYY',
                         DATENAME(YY, @Datetime))
    IF (CHARINDEX ('YY',@StringDate) > 0)
       SET @StringDate = REPLACE(@StringDate, 'YY',
                         RIGHT(DATENAME(YY, @Datetime),2))
    IF (CHARINDEX ('Month',@StringDate) > 0)
       SET @StringDate = REPLACE(@StringDate, 'Month',
                         DATENAME(MM, @Datetime))
    IF (CHARINDEX ('MON',@StringDate COLLATE SQL_Latin1_General_CP1_CS_AS)>0)
       SET @StringDate = REPLACE(@StringDate, 'MON',
                         LEFT(UPPER(DATENAME(MM, @Datetime)),3))
    IF (CHARINDEX ('Mon',@StringDate) > 0)
       SET @StringDate = REPLACE(@StringDate, 'Mon',
                                     LEFT(DATENAME(MM, @Datetime),3))
    IF (CHARINDEX ('MM',@StringDate) > 0)
       SET @StringDate = REPLACE(@StringDate, 'MM',
                  RIGHT('0'+CONVERT(VARCHAR,DATEPART(MM, @Datetime)),2))
    IF (CHARINDEX ('M',@StringDate) > 0)
       SET @StringDate = REPLACE(@StringDate, 'M',
                         CONVERT(VARCHAR,DATEPART(MM, @Datetime)))
    IF (CHARINDEX ('DD',@StringDate) > 0)
       SET @StringDate = REPLACE(@StringDate, 'DD',
                         RIGHT('0'+DATENAME(DD, @Datetime),2))
    IF (CHARINDEX ('D',@StringDate) > 0)
       SET @StringDate = REPLACE(@StringDate, 'D',
                                     DATENAME(DD, @Datetime))   
RETURN @StringDate
END
GO
PRINT N'Creating [dbo].[f_prt_getParameter]...';


GO
-- =============================================
-- Author:		G:A:R
-- Create date: 
-- Description:	estrazione valore del paramento passato
-- =============================================
CREATE FUNCTION f_prt_getParameter 
(
	 @par AS VARCHAR(50)
    ,@val AS VARCHAR(50)
    ,@endSepar AS VARCHAR(10) = '&'
)
RETURNS VARCHAR(50)
AS
BEGIN

	DECLARE @Result VARCHAR(50)
    DECLARE @Inizio INT;
    DECLARE @Fine   INT;

    SET @par = '%'+ @par + '=%'      -- '%QuoteType=%'

    --;WITH CTE AS 
    --(
    --    SELECT *, ( PATINDEX(@campo , Chiave) + LEN(@campo) - 2 ) As Inizio , CHARINDEX ( '&' ,Chiave , PATINDEX(@campo , Chiave) ) As Fine
    --    FROM dbo.ReportPrintTicket
    --    WHERE Ticket = 1 AND PATINDEX(@campo , Chiave) > 0
    --)

    SET @Inizio = PATINDEX(@par , @val )    

    IF @Inizio > 0
      BEGIN 
        SET @Inizio = @Inizio + LEN(@par) - 2 
        SET @Fine = CASE WHEN ( CHARINDEX ( @endSepar , @val , @Inizio ) ) = 0 
                        THEN LEN(@val) 
                        ELSE CHARINDEX ( @endSepar , @val , @Inizio ) 
                    END ;
       
        SELECT @Result = SUBSTRING( @val, @Inizio, @Fine-@Inizio )
      END

   RETURN @Result
END
GO
PRINT N'Creating [dbo].[f_getDataCodPackag]...';


GO




-- =============================================
-- Author:		Steamware
-- Create date: 2014-01-30
-- Description:	Ritorna l'imballo e i dati associati ( sostituita da stored ma lasciata nel caso di query on-line )
-- =============================================
CREATE FUNCTION [dbo].[f_getDataCodPackag]
(
	@CodItem	NVARCHAR(50),
	@CodClient	NVARCHAR(50)
)
RETURNS 
@Table TABLE 
(
	[CodItem] [nvarchar](50) NOT NULL,
	[CodClient] [nvarchar](50) NOT NULL,
	[CodPackag] [nvarchar](50) NOT NULL,
	[TotQta] [decimal](18, 3) NOT NULL,
	[Weight] [decimal](18, 6) NOT NULL,
	[Tare] [decimal](18, 6) NOT NULL,
	[NumImb] [decimal](9, 6) NOT NULL,
	[Durata] [decimal](18, 6) NOT NULL,
	[LivPackag] [nvarchar](50) NOT NULL,
	[LivPackagDet] [nvarchar](50) NOT NULL
)
AS
BEGIN

	DECLARE @output NVARCHAR(50)
	DECLARE @trovati INT = 0
	-- setup iniziale: imposto a zero...
	SET		@output = '0'

 --   SELECT	@trovati = COUNT(*) FROM Package2ItemClient WHERE CodClient = @CodClient AND CodItem = @CodItem
	--IF(@trovati > 0)

	IF EXISTS ( SELECT * FROM dbo.Package2ItemClient WHERE CodClient = @CodClient AND CodItem = @CodItem)
    	-- primo tentativo: cerco il package dato SIA cliente che ITEM
		BEGIN
            INSERT @Table
			SELECT TOP 1 CodItem, CodClient , CodPackag, TotQta, Weight, Tare, NumImb, Durata
                        ,'Item-Client-Package', @CodItem + '-' + @CodClient + '-' + CodPackag
            FROM dbo.Package2ItemClient WHERE CodClient = @CodClient AND CodItem = @CodItem
			ORDER BY TotQta DESC
		END
	ELSE IF EXISTS ( SELECT * FROM Package2Item WHERE CodItem = @CodItem  )
		-- secondo tentativo: se non lo trovo cerco per SOLO ITEM
		BEGIN
            INSERT @Table
			SELECT TOP 1 CodItem, 'ND' AS CodClient , CodPackag, TotQta, Weight, Tare, NumImb, Durata
                        ,'Item-Package', @CodItem + '-' + CodPackag
            FROM dbo.Package2Item WHERE CodItem = @CodItem
			ORDER BY TotQta DESC
		END
    ELSE
		-- secondo tentativo: se non lo trovo cerco per SOLO ITEM
		BEGIN
            INSERT @Table
			SELECT TOP 1 'ND', 'ND' AS CodClient , CodPackag, TotQta, Weight, Tare, NumImb, Durata
                         ,'Package', CodPackag
            FROM dbo.Package2 WHERE CodPackag = 0
		END

	RETURN 
END
GO
PRINT N'Creating [dbo].[v_selClient]...';


GO
CREATE VIEW dbo.v_selClient
AS
SELECT        CodClient AS value, CASE WHEN LEN(ClientName) > 40 THEN SUBSTRING(ClientName, 0, 40) + '...' ELSE ClientName END + ' [' + CodClient + ']' AS label
FROM            dbo.ClientDet
WHERE        (CodClient <> '')
GO
PRINT N'Creating [dbo].[v_selIncoterms]...';


GO
CREATE VIEW dbo.v_selIncoterms
AS
SELECT        CodInco AS value, CodInco + ' - ' + Descript AS label
FROM            dbo.Incoterms
GO
PRINT N'Creating [dbo].[v_selCons]...';


GO
CREATE VIEW dbo.v_selCons
AS
SELECT        CodInco AS value, CodInco + ' - ' + Descript AS label
FROM            dbo.Incoterms
GO
PRINT N'Creating [dbo].[v_selRawMat]...';


GO

CREATE VIEW dbo.v_selRawMat
AS
SELECT        RawMat AS value, RawMat AS label
FROM            dbo.RawMatDet
WHERE        (RawMat <> '')
GO
PRINT N'Creating [dbo].[v_selItems]...';


GO
CREATE VIEW dbo.v_selItems
AS
SELECT        CodItem AS value, CodItem + ' - ' + ItemDescr AS label
FROM            dbo.ItemDet
WHERE        (CodItem <> '')
GO
PRINT N'Creating [dbo].[v_pivot]...';


GO

CREATE VIEW [dbo].[v_pivot]
AS

WITH ctePivotQuoteP 
AS (
    SELECT *
    FROM (
            SELECT QuoteType
                , CodQuote
                , QuoteRev
                , Descr
                , Parameter
            FROM dbo.QuoteParam
        ) AS SourceTable

    PIVOT(MIN(Parameter) FOR Descr IN (
          ItemDescr
        , CodifProfilo
        , ClasseMerc
        , CodClientAssoc
        , ClientNameAssoc
        , CodDiesGroup
        , TipoDies
        , DiamDies
        , HoleNumDies
        , NumDiesInList
        , NumDiesExaust
        , CodPlant
        , KeyAM
        , KeyAMIL
        , NumSMED
        , KgTeo
        , KgProdotti
        , QuotaMan
        , DiesPrice
        , DiesExpLife
        , DiesEOLife
		, DiesByClass
        , PkgDesc
        , PRMWeight
        , PWeight
        , PTare
        , TareStRatio
        , LivPackage
        , LivPackageDett
		-- START nuovi campi x SIM
        , DiesPrice_sim
        , SamplePrice
        , DiesFullCost
        , DiesPriceClientQuote
        , DiesTecLife
        , DiesCommLife
        , MonthSalesPrev
        , SalesPrevCost
        , DiesFinCost
        , ClientQuoteReven
        , ExtraDiscountDies
        , WSR01_sim
        , MSR01_sim
        , NetProd01_sim
		, DSR_sim
		-- end nuovi campi x SIM
        )
  ) AS PivotData
),
-- =================================================
-- PIVOT TABELLA QuoteOC
-- =================================================
ctePivotQuoteOC AS (   
    SELECT *
    FROM (
            SELECT    QuoteType
                    , CodQuote
                    , QuoteRev
                    , Class01 + ProcessNum AS ClassProc
                    , C4UG
            FROM dbo.QuoteOC
            ) AS SourceTable
    PIVOT(SUM(C4UG) FOR ClassProc IN 
              (   EE01
                , GAS01
                , MATRICE01
                , VENDITA01
                , ROTTAME01
                , VENDITA04
                , ROTTAME04
                , IMBALLO04
                , TRASPORTI04
                , PROVVIGIONI04
              ) 
       ) AS PivotData
)
-- =================================================
-- MAIN Select Tabella con INTO temp table
-- =================================================
SELECT 'V14.1' AS Vers
    , QL.QuoteType
    , QL.CodQuote
    , QL.QuoteRev
    , QL.IdxQState
    , QL.CodClient
    , CD.ClientName
    , QL.CodItem
    , QL.CodItemGroup
    , QL.RawMat
    , QL.UnitWeight
    , QL.BatchQty
    , QL.CodInco
    , CD.TranspZone
    , QL.KeyAM
    , QL.Note
    , QL.PriceOff
    , QL.OrdDate
    , QL.OrdNum
    , QL.OrdRow
    , QL.OrdPrice
    , QL.OrdQty
    , pQP.CodClientAssoc
    , pQP.ClientNameAssoc
    , pQP.ItemDescr
    , pQP.CodifProfilo
    , pQP.ClasseMerc
    , pQP.TipoDies
    , pQP.CodDiesGroup
    , CONVERT(DECIMAL(18,6),pQP.DiamDies)               AS DiamDies
    , CONVERT(INT,pQP.HoleNumDies)                      AS HoleNumDies
    , ISNULL(CONVERT(DECIMAL(18,6),pQP.DiesPrice),0)    AS DiesPrice
    , CONVERT(DECIMAL(18,6),pQP.DiesExpLife)            AS DiesExpLife
    , CONVERT(DECIMAL(18,6),pQP.DiesEOLife)             AS DiesEOLife
    , CONVERT(BIT, ISNULL(pQP.DiesByClass,0))           AS DiesByClass
    , CONVERT(DECIMAL(18,6),pQP.NumDiesInList)          AS NumDiesInList
    , CONVERT(DECIMAL(18,6),pQP.NumDiesExaust)          AS NumDiesExaust
    , pQP.CodPlant
    , pQP.KeyAMIL
    , CONVERT(DECIMAL(18,6),pQP.KgTeo)                  AS KgTeo
    , CONVERT(DECIMAL(18,6),pQP.NumSMED)                AS NumSMED
    , CONVERT(DECIMAL(18,6),pQP.QuotaMan)               AS QuotaMan
    , CONVERT(DECIMAL(18,6),pQP.PRMWeight)              AS PRMWeight
    , CONVERT(DECIMAL(18,6),pQP.PWeight)                AS PWeight
    , CONVERT(DECIMAL(18,6),pQP.PTare)                  AS PTare
    , pQP.LivPackage
    , pQP.LivPackageDett
	-- START nuovi campi x SIM
	, ISNULL(CONVERT(DECIMAL(18,6),pQP.DiesPrice_sim),0)            AS DiesPrice_sim
    , ISNULL(CONVERT(DECIMAL(18,6),pQP.SamplePrice),0)              AS SamplePrice
    , ISNULL(CONVERT(DECIMAL(18,6),pQP.DiesFullCost),0)             AS DiesFullCost
    , ISNULL(CONVERT(DECIMAL(18,6),pQP.DiesPriceClientQuote),0)     AS DiesPriceClientQuote
    , ISNULL(CONVERT(DECIMAL(18,6),pQP.DiesTecLife),0)              AS DiesTecLife
    , ISNULL(CONVERT(DECIMAL(18,6),pQP.DiesCommLife),1)             AS DiesCommLife
    , ISNULL(CONVERT(INT,pQP.MonthSalesPrev),0)                     AS MonthSalesPrev
    , ISNULL(CONVERT(DECIMAL(18,6),pQP.SalesPrevCost),0)            AS SalesPrevCost
    , ISNULL(CONVERT(DECIMAL(18,6),pQP.DiesFinCost),0)              AS DiesFinCost
    , ISNULL(CONVERT(DECIMAL(18,6),pQP.ClientQuoteReven),0)         AS ClientQuoteReven
    , ISNULL(CONVERT(DECIMAL(18,6),pQP.ExtraDiscountDies),0)        AS ExtraDiscountDies
    , ISNULL(CONVERT(DECIMAL(9,8),pQP.WSR01_sim),0)                 AS WSR01_sim
    , ISNULL(CONVERT(DECIMAL(9,8),pQP.MSR01_sim),0)                 AS MSR01_sim
    , ISNULL(CONVERT(DECIMAL(9,3),pQP.NetProd01_sim),0)             AS NetProd01_sim
	, ISNULL(CONVERT(DECIMAL(9,8),pQP.DSR_sim),0)                  AS DSR_sim
	-- end nuovi campi x SIM
    , QRM.RawMatCost
    , QRM.RawMatExtraCost
    , QRM.RawMatCost + QRM.RawMatExtraCost AS RawMatFullCost -- fare campo calcolato ?!?
    , QRM.CodPackag
    , pQP.PkgDesc
    , QRM.FSR
    , ISNULL(pQOC.PROVVIGIONI04, 0) AS ProvvCost
    , ISNULL(pQOC.EE01, 0)          AS EECost
    , ISNULL(pQOC.GAS01, 0)         AS GasCost
    , ISNULL(pQOC.MATRICE01, 0)     AS DiesCost
    , ISNULL(pQOC.IMBALLO04, 0)     AS PackCost
    , ISNULL(pQOC.TRASPORTI04, 0)   AS TranspCost
    , ISNULL(pQOC.VENDITA01, 0)     AS SellCost01
    , ISNULL(pQOC.ROTTAME01, 0)     AS RefCost01
    , ISNULL(pQOC.VENDITA04, 0)     AS SellCost04
    , ISNULL(pQOC.ROTTAME04, 0)     AS RefCost04
    , QWI01.WSR                     AS WSR01
    , QWI01.MSR                     AS MSR01
    , QWI01.NetProd                 AS NetProd01
    , QWI01.FC4UG                   AS FC4UG01
    , QWI01.VC4UG                   AS VC4UG01
    , QWI01.OH4UG                   AS OH4UG01
    , QWI01.SC4UG                   AS SC4UG01
    , 1 - (QWI01.DYR * QWI02.DYR * QWI03.DYR * QWI04.DYR) AS DSR
    , QWI04.NetProd                 AS NetProd04
    , QWI04.FC4UG                   AS FC4UG04
    , QWI04.VC4UG                   AS VC4UG04
    , ISNULL(pQOC.VENDITA01, 0) + ISNULL(pQOC.ROTTAME01, 0) + ISNULL(pQOC.VENDITA04, 0) + ISNULL(pQOC.ROTTAME04, 0) + ISNULL(pQOC.EE01, 0) + ISNULL(pQOC.GAS01, 0) + ISNULL(pQOC.MATRICE01, 0) + ISNULL(pQOC.IMBALLO04, 0) + ISNULL(pQOC.PROVVIGIONI04, 0) + ISNULL(pQOC.TRASPORTI04, 0) + QWI01.VC4UG + QWI04.VC4UG + QWI01.SC4UG AS FVC
    , PD.Charge
    , QL.valid
    , QL.errorScore

FROM dbo.QuoteList AS QL

INNER JOIN dbo.ClientDet CD
    ON QL.CodClient = CD.CodClient

INNER JOIN ctePivotQuoteP AS pQP
    ON      QL.QuoteType = pQP.QuoteType
        AND QL.CodQuote  = pQP.CodQuote
        AND QL.QuoteRev  = pQP.QuoteRev

INNER JOIN dbo.QuoteRM AS QRM
    ON      QL.QuoteType = QRM.QuoteType
        AND QL.CodQuote  = QRM.CodQuote
        AND QL.QuoteRev  = QRM.QuoteRev
        AND QL.rawmat    = QRM.RawMat

INNER JOIN  ctePivotQuoteOC AS pQOC
        ON      QL.QuoteType = pQOC.QuoteType
            AND QL.CodQuote  = pQOC.CodQuote
            AND QL.QuoteRev  = pQOC.QuoteRev

INNER JOIN dbo.QuoteWorkInt AS QWI01
    ON      QL.QuoteType = QWI01.QuoteType
        AND QL.CodQuote  = QWI01.CodQuote
        AND QL.QuoteRev  = QWI01.QuoteRev
        AND QWI01.ProcessNum = '01'
INNER JOIN dbo.QuoteWorkInt AS QWI02
    ON      QL.QuoteType = QWI02.QuoteType
        AND QL.CodQuote  = QWI02.CodQuote
        AND QL.QuoteRev  = QWI02.QuoteRev
        AND QWI02.ProcessNum = '02'
INNER JOIN dbo.QuoteWorkInt AS QWI03
    ON      QL.QuoteType = QWI03.QuoteType
        AND QL.CodQuote  = QWI03.CodQuote
        AND QL.QuoteRev  = QWI03.QuoteRev
        AND QWI03.ProcessNum = '03'
INNER JOIN dbo.QuoteWorkInt AS QWI04
    ON      QL.QuoteType = QWI04.QuoteType
        AND QL.CodQuote  = QWI04.CodQuote
        AND QL.QuoteRev  = QWI04.QuoteRev
        AND QWI04.ProcessNum = '04'
INNER JOIN dbo.PlantsDet AS PD
    ON PD.CodPlant = pQP.CodPlant
GO
PRINT N'Creating [dbo].[v_selDateStdCost]...';


GO
CREATE VIEW dbo.v_selDateStdCost
AS
SELECT DISTINCT CONVERT(date, LEFT(CodQuote, 6)) AS label, LEFT(CodQuote, 6) AS value
FROM            dbo.QuoteFull_C
GO
PRINT N'Creating [dbo].[v_selPackage]...';


GO
CREATE VIEW dbo.v_selPackage
AS
SELECT        CodPackag AS value, PackagDesc AS label
FROM            dbo.PackagDet
GO
PRINT N'Creating [dbo].[v_selPlant]...';


GO
CREATE VIEW dbo.v_selPlant
AS
SELECT        CodPlant AS value, Descript AS label
FROM            dbo.PlantsDet
GO
PRINT N'Creating [dbo].[v_StdCostList]...';


GO
CREATE VIEW dbo.v_StdCostList
AS
SELECT        LEFT(CodQuote, 6) AS DataRif, Class01, Class02, CodItem, RawMat, CodPlant, CodDiesGroup, CodPackag, batchQty, CodInco, RawMatFullCost, FVC, FullCost
FROM            dbo.QuoteFull_C
GO
PRINT N'Creating [dbo].[v_listinoArticoli]...';


GO
CREATE VIEW dbo.v_listinoArticoli
AS
SELECT DISTINCT 
                         GETDATE() AS DataRif, 'C' AS QuoteType, '' AS CodClient, dbo.DiesDet.CodItem, CASE WHEN dbo.ProductionLog.RawMat = '' THEN '6060' ELSE dbo.ProductionLog.RawMat END AS RawMat, 
                         2.00 + dbo.RawMatDet.ExtraMatCost AS RawMatCost, 1000 AS batchQty, 'EXW' AS CodInco
FROM            dbo.DiesDet INNER JOIN
                         dbo.ProductionLog ON dbo.DiesDet.CodDies = dbo.ProductionLog.CodDies INNER JOIN
                         dbo.RawMatDet ON dbo.ProductionLog.RawMat = dbo.RawMatDet.RawMat
GO
PRINT N'Creating [dbo].[v_MarginReportStats]...';


GO
CREATE VIEW dbo.v_MarginReportStats
AS
SELECT        MIN(OrdDate) AS FromDate, MAX(OrdDate) AS ToDate, COUNT(*) AS NumOrderRows, COUNT(DISTINCT OrdNum) AS NumOrders, COUNT(DISTINCT CodItem) AS NumItem, COUNT(DISTINCT CodClient) 
                         AS NumClients
FROM            dbo.QuoteFull_R
GO
PRINT N'Creating [dbo].[v_MarginReportStatsNewData]...';


GO
CREATE VIEW dbo.[v_MarginReportStatsNewData]
AS
SELECT        MIN(OrdDate) AS FromDate, MAX(OrdDate) AS ToDate, COUNT(*) AS NumOrderRows, COUNT(DISTINCT OrdNum) AS NumOrders, COUNT(DISTINCT CodItem) AS NumItem, COUNT(DISTINCT CodClient) 
                         AS NumClients
FROM            ext.OrdersHistRaw
GO
PRINT N'Creating [dbo].[v_QuoteFull_Q]...';


GO
CREATE VIEW dbo.v_QuoteFull_Q
AS
SELECT Vers
	, QuoteType
	, CodQuote
	, QuoteRev
	, IdxQState
	, CodClient
	, ClientName
	, CodItem
	, CodItemGroup
	, RawMat
	, UnitWeight
	, BatchQty
	, CodInco
	, TranspZone
	, KeyAM
	, Note
	, PriceOff
	, CodClientAssoc
	, ClientNameAssoc
	, ItemDescr
	, CodifProfilo
	, ClasseMerc
	, TipoDies
	, CodDiesGroup
	, DiamDies
	, HoleNumDies
	, DiesPrice
	, DiesExpLife
	, DiesEOLife
	, DiesByClass
	, NumDiesInList
	, NumDiesExaust
	, CodPlant
	, KeyAMIL
	, KgTeo
	, NumSMED
	, QuotaMan
	, PRMWeight
	, PWeight
	, PTare
	, LivPackage
	, LivPackageDett
	, RawMatCost
	, RawMatExtraCost
	, RawMatFullCost
	, CodPackag
	, PkgDesc
	, FSR
	, ProvvCost
	, EECost
	, GasCost
	, DiesCost
	, PackCost
	, TranspCost
	, SellCost01
	, RefCost01
	, SellCost04
	, RefCost04
	, WSR01
	, MSR01
	, NetProd01
	, FC4UG01
	, VC4UG01
	, OH4UG01
	, SC4UG01
	, DSR
	, NetProd04
	, FC4UG04
	, VC4UG04
	, FVC
	, Charge
	, FVC + RawMatFullCost AS P_FVC
	, FC4UG01 + OH4UG01 AS CPS
	, FC4UG01 + OH4UG01 + FVC + RawMatFullCost AS P_CPS
	, FC4UG04 + FVC + RawMatFullCost AS P_FC4UG04
	, FVC + FC4UG01 + OH4UG01 + FC4UG04 AS FullCost
	, FVC + FC4UG01 + OH4UG01 + FC4UG04 + RawMatFullCost AS P_FullCost
	, Charge * (FVC + FC4UG01 + OH4UG01 + FC4UG04) AS MinPrice
	, Charge * (FVC + FC4UG01 + OH4UG01 + FC4UG04) + RawMatFullCost AS P_MinPrice
	, PriceOff + RawMatFullCost AS P_PriceOff
	, PriceOff - (FVC + FC4UG01 + OH4UG01 + FC4UG04) AS NetMar
	, CASE 
		WHEN (FC4UG01 + OH4UG01 + FC4UG04) = 0
			THEN 0
		ELSE (PriceOff - FVC) / (FC4UG01 + OH4UG01 + FC4UG04)
		END AS FCShield
	, CASE 
		WHEN PWeight = 0
			THEN 0
		ELSE (PRMWeight - PTare) * (PriceOff + RawMatFullCost) / PWeight
		END AS PckSur
	, valid
	, errorScore
	, DiesPrice_sim
	, SamplePrice
	, DiesFullCost
	, DiesPriceClientQuote
	, DiesTecLife
	, DiesCommLife
	, MonthSalesPrev
	, SalesPrevCost
	, DiesFinCost
	, ClientQuoteReven
	, ExtraDiscountDies
	, WSR01_sim
	, MSR01_sim
	, NetProd01_sim
	, NetProd04_sim
	, DSR_sim
	, PriceOff - (FVC + FC4UG01 + OH4UG01 + FC4UG04) - ExtraDiscountDies AS NetMar_sim
	, CASE 
		WHEN (FC4UG01 + OH4UG01 + FC4UG04) = 0
			THEN 0
		ELSE (PriceOff - FVC - ExtraDiscountDies) / (FC4UG01 + OH4UG01 + FC4UG04)
		END AS FCShield_sim
	, Charge * (FVC + FC4UG01 + OH4UG01 + FC4UG04) + ExtraDiscountDies AS MinPrice_sim
	, Charge * (FVC + FC4UG01 + OH4UG01 + FC4UG04) + RawMatFullCost + ExtraDiscountDies AS P_MinPrice_sim
FROM dbo.QuoteFull_S

UNION

SELECT Vers
	, QuoteType
	, CodQuote
	, QuoteRev
	, IdxQState
	, CodClient
	, ClientName
	, CodItem
	, CodItemGroup
	, RawMat
	, UnitWeight
	, BatchQty
	, CodInco
	, TranspZone
	, KeyAM
	, Note
	, PriceOff
	, CodClientAssoc
	, ClientNameAssoc
	, ItemDescr
	, CodifProfilo
	, ClasseMerc
	, TipoDies
	, CodDiesGroup
	, DiamDies
	, HoleNumDies
	, DiesPrice
	, DiesExpLife
	, DiesEOLife
	, DiesByClass
	, NumDiesInList
	, NumDiesExaust
	, CodPlant
	, KeyAMIL
	, KgTeo
	, NumSMED
	, QuotaMan
	, PRMWeight
	, PWeight
	, PTare
	, LivPackage
	, LivPackageDett
	, RawMatCost
	, RawMatExtraCost
	, RawMatFullCost
	, CodPackag
	, PkgDesc
	, FSR
	, ProvvCost
	, EECost
	, GasCost
	, DiesCost
	, PackCost
	, TranspCost
	, SellCost01
	, RefCost01
	, SellCost04
	, RefCost04
	, WSR01
	, MSR01
	, NetProd01
	, FC4UG01
	, VC4UG01
	, OH4UG01
	, SC4UG01
	, DSR
	, NetProd04
	, FC4UG04
	, VC4UG04
	, FVC
	, Charge
	, FVC + RawMatFullCost AS P_FVC
	, FC4UG01 + OH4UG01 AS CPS
	, FC4UG01 + OH4UG01 + FVC + RawMatFullCost AS P_CPS
	, FC4UG04 + FVC + RawMatFullCost AS P_FC4UG04
	, FVC + FC4UG01 + OH4UG01 + FC4UG04 AS FullCost
	, FVC + FC4UG01 + OH4UG01 + FC4UG04 + RawMatFullCost AS P_FullCost
	, Charge * (FVC + FC4UG01 + OH4UG01 + FC4UG04) AS MinPrice
	, Charge * (FVC + FC4UG01 + OH4UG01 + FC4UG04) + RawMatFullCost AS P_MinPrice
	, PriceOff + RawMatFullCost AS P_PriceOff
	, PriceOff - (FVC + FC4UG01 + OH4UG01 + FC4UG04) AS NetMar
	, CASE 
		WHEN (FC4UG01 + OH4UG01 + FC4UG04) = 0
			THEN 0
		ELSE (PriceOff - FVC) / (FC4UG01 + OH4UG01 + FC4UG04)
		END AS FCShield
	, CASE 
		WHEN PWeight = 0
			THEN 0
		ELSE (PRMWeight - PTare) * (PriceOff + RawMatFullCost) / PWeight
		END AS PckSur
	, valid
	, errorScore
	, 0.0 AS DiesPrice_sim
	, 0.0 AS SamplePrice
	, 0.0 AS DiesFullCost
	, 0.0 AS DiesPriceClientQuote
	, 0.0 AS DiesTecLife
	, 0.0 AS DiesCommLife
	, 0.0 AS MonthSalesPrev
	, 0.0 AS SalesPrevCost
	, 0.0 AS DiesFinCost
	, 0.0 AS ClientQuoteReven
	, 0.0 AS ExtraDiscountDies
	, 0.0 AS WSR01_sim
	, 0.0 AS MSR01_sim
	, 0.0 AS NetProd01_sim
	, 0.0 AS NetProd04_sim
	, 0.0 AS DSR_sim
	, 0.0 AS NetMar_sim
	, 0.0 AS FCShield_sim
	, 0.0 AS MinPrice_sim
	, 0.0 AS P_MinPrice_sim
FROM dbo.QuoteFull_Q
GO
PRINT N'Creating [dbo].[v_selListVal]...';


GO
CREATE VIEW dbo.v_selListVal
AS
SELECT        TableName + '-' + FieldName + '-' + value AS value, label
FROM            dbo.ListValues
GO
PRINT N'Creating [dbo].[v_MarginReport]...';


GO
CREATE VIEW dbo.v_MarginReport
AS
SELECT        Vers, CodClient, CodItem, RawMat, BatchQty, CodInco, KeyAM, CodDiesGroup, DiesPrice, DiesExpLife, DiesEOLife, DiesByClass, NumDiesInList, NumDiesExaust, CodPlant, KeyAMIL, KgTeo, NumSMED, 
                         QuotaMan, PWeight, PTare, LivPackage, LivPackageDett, RawMatCost, RawMatExtraCost, RawMatFullCost, CodPackag, FSR, ProvvCost, EECost, GasCost, DiesCost, PackCost, TranspCost, SellCost01, 
                         RefCost01, SellCost04, RefCost04, WSR01, MSR01, NetProd01, FC4UG01, VC4UG01, OH4UG01, SC4UG01, DSR, NetProd04, FC4UG04, VC4UG04, FVC, Charge, FVC + RawMatFullCost AS P_FVC, 
                         FC4UG01 + OH4UG01 AS CPS, FC4UG01 + OH4UG01 + FVC + RawMatFullCost AS P_CPS, FC4UG04 + FVC + RawMatFullCost AS P_FC4UG04, FVC + FC4UG01 + OH4UG01 + FC4UG04 AS FullCost, 
                         FVC + FC4UG01 + OH4UG01 + FC4UG04 + RawMatFullCost AS P_FullCost, Charge * (FVC + FC4UG01 + OH4UG01 + FC4UG04) AS MinPrice, Charge * (FVC + FC4UG01 + OH4UG01 + FC4UG04) 
                         + RawMatFullCost AS P_MinPrice, PriceOff - (FVC + FC4UG01 + OH4UG01 + FC4UG04) AS NetMar, CASE WHEN (FC4UG01 + OH4UG01 + FC4UG04) = 0 THEN 0 ELSE (PriceOff - FVC) 
                         / (FC4UG01 + OH4UG01 + FC4UG04) END AS FCShield, CASE WHEN PWeight = 0 THEN 0 ELSE (PRMWeight - PTare) * (PriceOff + RawMatFullCost) / PWeight END AS PckSur, valid, errorScore, OrdDate, OrdNum, 
                         OrdRow, OrdPrice, PriceOff AS OrdTrasf, OrdQty
FROM            dbo.QuoteFull_R
GO
PRINT N'Creating [ext].[v_MarginReportRcd]...';


GO
CREATE VIEW ext.v_MarginReportRcd
AS
SELECT        dbo.v_MarginReport.Vers, ext.RcdClient.CodClientRcd AS CodClient, ext.RcdItem.CodItemRcd AS CodItem, dbo.v_MarginReport.RawMat, dbo.v_MarginReport.BatchQty, dbo.v_MarginReport.CodInco, 
                         ext.RcdItem.CodItemRcd + '-' + dbo.v_MarginReport.RawMat AS KeyAM, dbo.v_MarginReport.CodDiesGroup, dbo.v_MarginReport.DiesPrice, dbo.v_MarginReport.DiesExpLife, dbo.v_MarginReport.DiesEOLife, 
                         dbo.v_MarginReport.DiesByClass, dbo.v_MarginReport.NumDiesInList, dbo.v_MarginReport.NumDiesExaust, ext.RcdPlants.CodPlantRcd AS CodPlant, 
                         ext.RcdItem.CodItemRcd + '-' + dbo.v_MarginReport.RawMat + '-' + ext.RcdPlants.CodPlantRcd + '-' + RIGHT(dbo.v_MarginReport.KeyAMIL, 1) AS KeyAMIL, dbo.v_MarginReport.KgTeo, 
                         dbo.v_MarginReport.NumSMED, dbo.v_MarginReport.QuotaMan, dbo.v_MarginReport.PWeight, dbo.v_MarginReport.PTare, dbo.v_MarginReport.LivPackage, 
                         REPLACE(REPLACE(dbo.v_MarginReport.LivPackageDett, dbo.v_MarginReport.CodItem, ext.RcdItem.CodItemRcd), dbo.v_MarginReport.CodClient, ext.RcdClient.CodClientRcd) AS LivPackageDett, 
                         dbo.v_MarginReport.RawMatCost, dbo.v_MarginReport.RawMatExtraCost, dbo.v_MarginReport.RawMatFullCost, dbo.v_MarginReport.CodPackag, dbo.v_MarginReport.FSR, dbo.v_MarginReport.ProvvCost, 
                         dbo.v_MarginReport.EECost, dbo.v_MarginReport.GasCost, dbo.v_MarginReport.DiesCost, dbo.v_MarginReport.PackCost, dbo.v_MarginReport.TranspCost, dbo.v_MarginReport.SellCost01, 
                         dbo.v_MarginReport.RefCost01, dbo.v_MarginReport.SellCost04, dbo.v_MarginReport.RefCost04, dbo.v_MarginReport.WSR01, dbo.v_MarginReport.MSR01, dbo.v_MarginReport.NetProd01, 
                         dbo.v_MarginReport.FC4UG01, dbo.v_MarginReport.VC4UG01, dbo.v_MarginReport.OH4UG01, dbo.v_MarginReport.SC4UG01, dbo.v_MarginReport.DSR, dbo.v_MarginReport.NetProd04, 
                         dbo.v_MarginReport.FC4UG04, dbo.v_MarginReport.VC4UG04, dbo.v_MarginReport.FVC, dbo.v_MarginReport.Charge, dbo.v_MarginReport.P_FVC, dbo.v_MarginReport.CPS, dbo.v_MarginReport.P_CPS, 
                         dbo.v_MarginReport.P_FC4UG04, dbo.v_MarginReport.FullCost, dbo.v_MarginReport.P_FullCost, dbo.v_MarginReport.MinPrice, dbo.v_MarginReport.P_MinPrice, dbo.v_MarginReport.NetMar, 
                         dbo.v_MarginReport.FCShield, dbo.v_MarginReport.PckSur, dbo.v_MarginReport.valid, dbo.v_MarginReport.errorScore, dbo.v_MarginReport.OrdDate, 'ORD' + REPLACE(REPLACE(dbo.v_MarginReport.OrdNum, 
                         '11', '21'), '12', '22') AS OrdNum, dbo.v_MarginReport.OrdRow, dbo.v_MarginReport.OrdPrice, dbo.v_MarginReport.OrdTrasf, dbo.v_MarginReport.OrdQty
FROM            dbo.v_MarginReport INNER JOIN
                         ext.RcdClient ON dbo.v_MarginReport.CodClient = ext.RcdClient.CodClient INNER JOIN
                         ext.RcdItem ON dbo.v_MarginReport.CodItem = ext.RcdItem.CodItem INNER JOIN
                         ext.RcdPlants ON dbo.v_MarginReport.CodPlant = ext.RcdPlants.CodPlant
GO
PRINT N'Creating [ext].[v_ItemDetRcd]...';


GO
CREATE VIEW ext.v_ItemDetRcd
AS
SELECT        ext.RcdItem.CodItemRcd AS CodItem, ext.RcdItem.ItemDescrRcd AS ItemDescr, ext.RcdItem.CodPlantRcd AS CodPlant, dbo.ItemDet.UnitWeight, dbo.ItemDet.CodItemGroup, 
                         ext.RcdClass01.CodClass01Rcd AS Class01, ext.RcdClass02.CodClass02Rcd AS Class02, '' AS Class03, '' AS Class04, '' AS Class05
FROM            dbo.ItemDet INNER JOIN
                         ext.RcdItem ON dbo.ItemDet.CodItem = ext.RcdItem.CodItem INNER JOIN
                         ext.RcdClass01 ON dbo.ItemDet.Class01 = ext.RcdClass01.CodClass01 INNER JOIN
                         ext.RcdClass02 ON dbo.ItemDet.Class02 = ext.RcdClass02.CodClass02
GO
PRINT N'Creating [ext].[v_ClientDetRcd]...';


GO
CREATE VIEW ext.v_ClientDetRcd
AS
SELECT        ext.RcdClient.CodClientRcd AS CodClient, ext.RcdClient.ClientNameRcd AS ClientName, ext.RcdClient.CodAgRcd AS CodAg, dbo.ClientDet.ZipCode, dbo.ClientDet.City, dbo.ClientDet.State, dbo.ClientDet.Nation, 
                         dbo.ClientDet.TranspZone
FROM            dbo.ClientDet INNER JOIN
                         ext.RcdClient ON dbo.ClientDet.CodClient = ext.RcdClient.CodClient
GO
PRINT N'Creating [dbo].[stp_packageCost]...';


GO


-- =============================================
-- Author:		S.E. Locatelli
-- Create date: 2014.01.15
-- Description:	stp_packageCost
-- SOSTITUITA da query + funzione
-- =============================================
CREATE PROCEDURE [dbo].[stp_packageCost] 
(
	@CodItem	NVARCHAR(50) = '', 
	@CodClient	NVARCHAR(50) = '',
	@CodPackag	NVARCHAR(50) = '',
	@PDesc		NVARCHAR(50) OUTPUT,
	@RMWeight	DECIMAL(9,4) OUTPUT,
	@Weight		DECIMAL(9,4) OUTPUT,
	@Tare		DECIMAL(9,4) OUTPUT,
	@PackCost	DECIMAL(9,6) OUTPUT,
	@TareStRat	DECIMAL(9,4) OUTPUT
)
AS
BEGIN
	SET NOCOUNT ON;

	DECLARE @trovati	INT = 0,
			@RMCost		DECIMAL(9,3)

	-- calcolo RMCost e RMWeight da tab PackageDet
	SELECT	@RMCost = RMCost, @RMWeight = RMWeight, @PDesc= PackagDesc
	FROM	PackagDet
	WHERE	CodPackag = @CodPackag

	-- Calcolo peso e tara da selezione gerarchica
	SELECT	@trovati = COUNT(*) 
    FROM Package2ItemClient WHERE CodItem = @CodItem AND CodClient = @CodClient AND CodPackag = @CodPackag

	IF(@trovati > 0)
		-- primo tentativo: cerco il package dato SIA Cliente che Item che Package
		BEGIN
			SELECT	TOP 1	@Weight = [Weight], @Tare = Tare
			FROM			Package2ItemClient WHERE CodItem = @CodItem AND CodClient = @CodClient AND CodPackag = @CodPackag
			ORDER BY		TotQta DESC
		END
	ELSE
		-- secondo tentativo: se non lo trovo cerco per SOLO ITEM e package
		BEGIN
			SELECT	@trovati = COUNT(*) FROM Package2Item WHERE CodItem = @CodItem AND CodPackag = @CodPackag
			IF(@trovati > 0)
				BEGIN
					SELECT	TOP 1	@Weight = [Weight], @Tare = Tare
					FROM			Package2Item WHERE CodItem = @CodItem AND CodPackag = @CodPackag
					ORDER BY		TotQta DESC
				END
			ELSE
				BEGIN
					SELECT			@Weight = [Weight], @Tare = Tare
					FROM			Package2 WHERE CodPackag = @CodPackag
				END
		END


	-- faccio ultimi calcoli!
	SELECT	@PackCost = @RMCost / @Weight, @TareStRat = (@RMWeight - @Tare) / @Weight

END
GO
PRINT N'Creating [dbo].[stp_esplodiVocab]...';


GO
-- =============================================
-- Author:		S.E.Locatelli
-- Create date: 2011-10-24
-- Description:	
-- =============================================
create PROCEDURE stp_esplodiVocab 
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	
	-- svuoto vocabolario
	DELETE FROM ZZZ_VocabExpl
	
	-- carico termini ITA
	INSERT INTO ZZZ_VocabExpl(Lemma,IT)
	SELECT	Lemma, Traduzione AS IT 
	FROM	Vocabolario
	WHERE	Lingua = 'IT'
	
	-- update termini ENG
	UPDATE	ZZZ_VocabExpl
	SET		EN=ISNULL(v.Traduzione,ve.EN)
	FROM	ZZZ_VocabExpl ve INNER JOIN Vocabolario v ON ve.Lemma=v.Lemma
	WHERE	v.Lingua='EN'
	
	-- update termini BRA
	UPDATE	ZZZ_VocabExpl
	SET		BR=ISNULL(v.Traduzione,ve.BR)
	FROM	ZZZ_VocabExpl ve INNER JOIN Vocabolario v ON ve.Lemma=v.Lemma
	WHERE	v.Lingua='BR'

	-- update termini CHN
	UPDATE	ZZZ_VocabExpl
	SET		CN=ISNULL(v.Traduzione,ve.CN)
	FROM	ZZZ_VocabExpl ve INNER JOIN Vocabolario v ON ve.Lemma=v.Lemma
	WHERE	v.Lingua='CN'
	
	-- update termini CHN
	UPDATE	ZZZ_VocabExpl
	SET		MX=ISNULL(v.Traduzione,ve.MX)
	FROM	ZZZ_VocabExpl ve INNER JOIN Vocabolario v ON ve.Lemma=v.Lemma
	WHERE	v.Lingua='MX'
	
	-- update termini CHN
	UPDATE	ZZZ_VocabExpl
	SET		PL=ISNULL(v.Traduzione,ve.PL)
	FROM	ZZZ_VocabExpl ve INNER JOIN Vocabolario v ON ve.Lemma=v.Lemma
	WHERE	v.Lingua='PL'


END
GO
PRINT N'Creating [dbo].[stp_VSCli_SearchLike]...';


GO
-- =============================================
-- Author:		S.E. Locatelli
-- Create date: 2014.02.11
-- Description:	Ricerca clienti
-- =============================================
CREATE PROCEDURE [dbo].stp_VSCli_SearchLike
(
	@value NVARCHAR(50)
)

AS
SET NOCOUNT ON;

SELECT value
	,label
FROM v_selClient
WHERE (value LIKE '%' + @value + '%')
	OR (label LIKE '%' + @value + '%')
GO
PRINT N'Creating [dbo].[stp_QL_update_07_02]...';


GO




-- =============================================
-- Author:		Steamware
-- Create date: 2014.01.22
-- Description:	aggiorna le tabelle QuoteList con i dati selezionati dalla TabProdSc
-- =============================================
CREATE PROCEDURE [dbo].[stp_QL_update_07_02]
(
	@QuoteType	CHAR(1) = 'Q',
	@CodQuote	BIGINT	= 0,
	@QuoteRev	INT		= 0
) 
AS
BEGIN

    SET NOCOUNT ON;

	-- dichiaro valori da recuperare
	DECLARE	@strTemp		NVARCHAR(50) = '' --stringa temporanea x variabili "locali"

	DECLARE @valid			BIT
	DECLARE @CodDiesGroup	NVARCHAR(50)
	DECLARE @CodPlant		NVARCHAR(50)
	DECLARE @CodPlantFix	NVARCHAR(50) = ''
	DECLARE @HoleNum		INT
    -- ITEM
	DECLARE @CodItem		NVARCHAR(50) = '' --cod item
	DECLARE @ItemDescr		NVARCHAR(50) = '' -- descrizione item
    DECLARE @CodifProfilo   NVARCHAR(50) = '' -- Cod. Profilo
    DECLARE @ClasseMerc     NVARCHAR(50) = '' 
    DECLARE @CodClientAssoc NVARCHAR(50) = '' 

	DECLARE @KeyAM			NVARCHAR(50) = ''
	DECLARE @KeyAMI			NVARCHAR(50) = ''
	DECLARE @KeyAMIL		NVARCHAR(50) = ''
	DECLARE @NumSMED		INT = 0 -- numero cambi
	DECLARE @KgTeo			DECIMAL(18, 6) = 0 -- kg totali
	DECLARE @RawMat			NVARCHAR(50)
	DECLARE	@ProdTeo		DECIMAL(18,6)
	DECLARE	@ScTec			DECIMAL(18,6)
	DECLARE	@BatchQty		INT
	DECLARE	@MAC_SC			DECIMAL(18,6) -- Messa a cento scarto cesoia
	DECLARE	@MAC_ST			DECIMAL(18,6) -- Messa a cento scarto tecnico
	DECLARE	@MAC_IN			DECIMAL(18,6) -- Messa a cento difettosità all'incestatura
	DECLARE	@MAC_IM			DECIMAL(18,6) -- Messa a cento difettosità all'imballo
	DECLARE	@SSR			DECIMAL(9,6) -- percentuale vendita rottame
	DECLARE	@DiesPrice		DECIMAL(9,3) -- prezzo matrice
	DECLARE	@DiesEOLife		DECIMAL(9,2) -- durata matrice
	DECLARE	@DiesExpLife	DECIMAL(9,2) -- durata matrice
	DECLARE	@DiesPriceLife	DECIMAL(18,6) -- Price/Life matrice
	DECLARE	@OCF01			DECIMAL(18,6) = 0 -- altri costi di fase 01
	DECLARE	@VCF01			DECIMAL(18,6) = 0 -- costi variabili di fase 01
	DECLARE	@VCF04			DECIMAL(18,6) = 0 -- costi variabili di fase 04
	DECLARE	@SellCostF01	DECIMAL(18,6) = 0 -- costo vendita fase 01
	DECLARE	@SellCostF04	DECIMAL(18,6) = 0 -- costo vendita fase 04
	DECLARE	@RefCostF01		DECIMAL(18,6) = 0 -- costo rifusione fase 01 
	DECLARE	@RefCostF04		DECIMAL(18,6) = 0 -- costo rifusione fase 04
	-- IMBALLO
	DECLARE	@CodPackag		NVARCHAR(50) = '0'  -- codice dell'imballo
	DECLARE @CodClient		NVARCHAR(50) = ''   -- codice cliente
	DECLARE @NumImb			DECIMAL(9,6) = 0    -- num imballatori
	DECLARE @PkgDesc		NVARCHAR(50) = ''   -- descrizione imballo
	DECLARE @PRMWeight		DECIMAL(9,4) = 0    -- peso dell'imballo
	DECLARE @PWeight		DECIMAL(9,4) = 0    -- peso del pacco
	DECLARE @PTare			DECIMAL(9,4) = 0    -- media delal tara di imballo dichiarata
	DECLARE @PCost			DECIMAL(9,6) = 0    -- costo unitario dell'imballo (al kg) 
	DECLARE @PTareStRatio	DECIMAL(9,4) = 0    -- coefficiente di recupero tara/prodotto
    DECLARE @PTotQta        DECIMAL(18,3) = 0   -- Qta Kg Tot Imballati
    DECLARE @PDurata        DECIMAL(18,6) = 0   -- Tempo d'imballaggio
    DECLARE @PLiv           NVARCHAR(50)  = ''   -- Livello Search dati Imballo     
    DECLARE @PLivDett       NVARCHAR(50)  = ''   -- Key Livello Search Dati Imballo
	-- TRASPORTI
	DECLARE	@TranspZone		NVARCHAR(50) = '' -- codice ZONA
    DECLARE	@TranspCost		DECIMAL(9,6)      -- costo di trasporto
    DECLARE	@HasTC			INT

	-- PROVVIGIONI
	DECLARE	@Provvig		DECIMAL(9,6) -- provvigione agente

	-- default: validità è true!
	SET		@valid = 1

    -- =================================================
    --   CREAZIONE TEMP TABLE
    -- =================================================

	-- elimino e ricreo #QuoteParam temp table...
	IF OBJECT_ID('tempdb..#QuoteParam') IS NOT NULL
		DROP TABLE #QuoteParam

	CREATE TABLE #QuoteParam
	(
		[QuoteType] [char](1) NOT NULL,
		[CodQuote] [bigint] NOT NULL,
		[QuoteRev] [int] NOT NULL,
		[NumP] [int] IDENTITY(1,1) NOT NULL,
		[ProcessNum] [nvarchar](50) NOT NULL,
		[Descr] [nvarchar](50) NOT NULL,
		[Parameter] [nvarchar](100) NOT NULL,
	--PRIMARY KEY
	--		(	[NumP] ASC, [QuoteType] ASC, [CodQuote] ASC, [QuoteRev] ASC ) WITH  (PAD_INDEX  = ON, FILLFACTOR = 90 )
	 )

	-- elimino e ricreo #QuoteParam temp table...
	IF OBJECT_ID('tempdb..#QuoteWorkInt') IS NOT NULL
		DROP TABLE #QuoteWorkInt

   CREATE TABLE #QuoteWorkInt
    (
        [QuoteType]     [char](1) NOT NULL,
        [CodQuote]      [bigint] NOT NULL,
        [QuoteRev]      [int] NOT NULL,
        [NumWI]         [int] IDENTITY(1,1) NOT NULL,
        [ProcessNum]    [nvarchar](50) NOT NULL,
        [CodPlant]      [nvarchar](50) NOT NULL,
        [Class01]       [nvarchar](50) NOT NULL DEFAULT (''),
        [Class02]       [nvarchar](50) NOT NULL DEFAULT (''),
        [Class03]       [nvarchar](50) NOT NULL DEFAULT (''),
        [Class04]       [nvarchar](50) NOT NULL DEFAULT (''),
        [Class05]       [nvarchar](50) NOT NULL DEFAULT (''),
        [NetProd]       [decimal](9, 3) NOT NULL DEFAULT ((0)),
        [WSR]           [decimal](9, 8) NOT NULL DEFAULT ((0)),
        [MSR]           [decimal](9, 8) NOT NULL DEFAULT ((0)),
        [DSR]           [decimal](9, 8) NOT NULL DEFAULT ((0)),
        [FC4UG]         [decimal](9, 6) NOT NULL DEFAULT ((0)),
        [VC4UG]         [decimal](9, 6) NOT NULL DEFAULT ((0)),
        [OH4UG]         [decimal](9, 6) NOT NULL DEFAULT ((0)),
        [SC4UG]         [decimal](9, 6) NOT NULL DEFAULT ((0)),
        [WYR]   AS ((1)-[WSR]),
        [MYR]   AS ((1)-[MSR]),
        [DYR]   AS ((1)-[DSR]),
        [WCR]   AS ((1)/((1)-[WSR])),
        [MCR]   AS ((1)/((1)-[MSR])),
        [DCR]   AS ((1)/((1)-[DSR])),
        [valid] [bit] NOT NULL DEFAULT((1)),
    )

    -- elimino e ricreo #QuoteParam temp table...
    IF OBJECT_ID('tempdb..#QuoteOC') IS NOT NULL
		DROP TABLE #QuoteOC

    CREATE TABLE #QuoteOC 
    (
	    [QuoteType] [char](1) NOT NULL,
	    [CodQuote]  [bigint] NOT NULL,
	    [QuoteRev]  [int] NOT NULL,
	    [NumEx]     [int] IDENTITY(1,1) NOT NULL,
	    [ProcessNum] [nvarchar](50)     NOT NULL,
	    [CodPlant]  [nvarchar](50)      NOT NULL,
	    [Class01]   [nvarchar](50)      NOT NULL DEFAULT (''),
	    [Class02]   [nvarchar](50)      NOT NULL DEFAULT (''),
	    [Class03]   [nvarchar](50)      NOT NULL DEFAULT (''),
	    [Class04]   [nvarchar](50)      NOT NULL DEFAULT (''),
	    [Class05]   [nvarchar](50)      NOT NULL DEFAULT (''),
	    [TotQty]    [decimal](18, 6)    NOT NULL DEFAULT ((1)),
	    [TotCost]   [decimal](18, 6)    NOT NULL DEFAULT ((0)),
	    [Quota]     [decimal](18, 6)    NOT NULL DEFAULT ((1)),
	    [C4UG]  AS (([TotCost]*[Quota])/[TotQty]),
	    [valid]     [bit] NOT NULL DEFAULT ((1))
    )

    -- ===================================
    --  INIZIO TRANSAZIONE
    -- ===================================
	SET XACT_ABORT ON;
	BEGIN TRAN

		---------------------------------------
		-- svuotamento iniziale
		---------------------------------------
	
		-- elimino quote PARAMETRI!
		DELETE FROM	dbo.QuoteParam
		WHERE	QuoteType	= @QuoteType
			AND	CodQuote	= @CodQuote
			AND	QuoteRev	= @QuoteRev

    	-- elimino lavorazioni ESTERNE!
		DELETE FROM	dbo.QuoteWorkExt
		WHERE	QuoteType	= @QuoteType
			AND	CodQuote	= @CodQuote
			AND	QuoteRev	= @QuoteRev

		-- elimino lavorazioni INTERNE
		DELETE FROM	dbo.QuoteWorkInt
		WHERE	QuoteType	= @QuoteType
			AND	CodQuote	= @CodQuote
			AND	QuoteRev	= @QuoteRev

		-- elimino OtherCosts
		DELETE FROM	dbo.QuoteOC
		WHERE	QuoteType	= @QuoteType
			AND	CodQuote	= @CodQuote
			AND	QuoteRev	= @QuoteRev

		-- se ci sono eccezioni nella tab dell'anagrafico articoli imposto il codPlant desiderato
		SET	@CodPlantFix = ISNULL ( ( SELECT id.CodPlant FROM dbo.ItemDet id 
                                      INNER JOIN dbo.QuoteList ql ON id.CodItem = ql.CodItem
		                              WHERE ql.QuoteType   = @QuoteType
			                            AND ql.CodQuote    = @CodQuote
			                            AND ql.QuoteRev    = @QuoteRev ), '' )

		-- recupero da dati dell'offerta il valore del cliente
		SELECT	@CodClient		= CodClient
		FROM	dbo.QuoteList
		WHERE	QuoteType		= @QuoteType
			AND	CodQuote		= @CodQuote
			AND	QuoteRev		= @QuoteRev
        
		-- recupero dati!!
		SELECT	TOP 1 @CodItem	= ql.CodItem
					, @CodDiesGroup = tps.CodDiesGroup
                    , @CodPlant     = CASE WHEN @CodPlantFix <> '' THEN @CodPlantFix ELSE tps.CodPlant END
					, @HoleNum      = tps.HoleNum
					, @KeyAM	    = ql.KeyAM
					, @KeyAMI	    = ql.KeyAM + '-' + ISNULL(@CodPlant,'0000')
					, @KeyAMIL	    = ql.KeyAM + '-' + ISNULL(@CodPlant,'0000') + '-' + CAST(ISNULL(tps.HoleNum,0) AS NVARCHAR(10))
					, @ProdTeo	    = tps.ProdTeo
					, @ScTec	    = tps.ScTec
					, @KgTeo	    = tps.KgTeo
					, @NumSMED	    = tps.NumSMED
					, @RawMat	    = ql.RawMat
					, @BatchQty	    = ql.BatchQty
					, @ItemDescr    = i.ItemDescr
                    , @CodifProfilo = i.Class01
                    , @ClasseMerc   = i.Class02
                    , @CodClientAssoc = i.Class03

		FROM dbo.QuoteList ql 
        INNER JOIN dbo.TabProdSc tps ON ql.KeyAM = tps.KeyAM 
        INNER JOIN dbo.ItemDet i ON ql.CodItem = i.CodItem
		WHERE	ql.QuoteType	= @QuoteType
			AND	ql.CodQuote		= @CodQuote
			AND	ql.QuoteRev		= @QuoteRev
		ORDER BY tps.KgTeo DESC
		
        -- =================================================================================
		-- recupero dall'offerta il valore del PACKAGE/IMBALLO scelto e i dati relativi
        -- Secondo la logica Client-Item-Package ( vedi funzione )
        -- =================================================================================
        -- SET @CodPackag = ( SELECT dbo.f_getCodPackag( @CodItem , @CodClient ) )
        -- attenzione è una function tabellare
        SELECT @CodPackag = CodPackag, @PTotQta = TotQta, @PWeight = [Weight], @PTare = Tare,
               @NumImb = NumImb, @PDurata = Durata, @PLiv = LivPackag , @PLivDett = LivPackagDet
        FROM f_getDataCodPackag ( @CodItem, @CodClient)

        -- e aggiorno il CodPackage in QuoteRM
		UPDATE	dbo.QuoteRM
        SET CodPackag = @CodPackag
		FROM	dbo.QuoteRM
		WHERE	QuoteType		= @QuoteType
			AND	CodQuote		= @CodQuote
			AND	QuoteRev		= @QuoteRev

		INSERT INTO #QuoteParam(QuoteType, CodQuote, QuoteRev, ProcessNum, Descr, Parameter)
		VALUES (@QuoteType, @CodQuote, @QuoteRev, '01', 'ItemDescr', @ItemDescr)

		INSERT INTO #QuoteParam(QuoteType, CodQuote, QuoteRev, ProcessNum, Descr, Parameter)
		SELECT	@QuoteType, @CodQuote, @QuoteRev, '01', 'CodifProfilo', @CodifProfilo
		--FROM	dbo.ItemDet
		--WHERE	CodItem = @CodItem

		INSERT INTO #QuoteParam(QuoteType, CodQuote, QuoteRev, ProcessNum, Descr, Parameter)
		SELECT	@QuoteType, @CodQuote, @QuoteRev, '01', 'ClasseMerc', @ClasseMerc
		--FROM	dbo.ItemDet
		--WHERE	CodItem	= @CodItem
		
		INSERT INTO #QuoteParam(QuoteType, CodQuote, QuoteRev, ProcessNum, Descr, Parameter)
		SELECT	@QuoteType, @CodQuote, @QuoteRev, '01', 'CodClientAssoc', @CodClientAssoc
		--FROM	dbo.ItemDet
		--WHERE	CodItem	= @CodItem
        
		INSERT INTO #QuoteParam(QuoteType, CodQuote, QuoteRev, ProcessNum, Descr, Parameter)
		SELECT  @QuoteType, @CodQuote, @QuoteRev, '01', 'ClientNameAssoc', ClientDet.ClientName
        FROM dbo.ClientDet WHERE ClientDet.CodClient = @CodClientAssoc
		--FROM    dbo.ItemDet
        --INNER JOIN dbo.ClientDet ON ItemDet.Class03 = ClientDet.CodClient
		--WHERE   CodItem	= @CodItem
		
		-- INFORMAZIONI su MATRICE
		INSERT INTO #QuoteParam(QuoteType, CodQuote, QuoteRev, ProcessNum, Descr, Parameter)
		VALUES (@QuoteType, @CodQuote, @QuoteRev, '01', 'CodDiesGroup', @CodDiesGroup )

		SET @strTemp = dbo.f_getSubstring(@CodDiesGroup, '-', 1) 
		INSERT INTO #QuoteParam(QuoteType, CodQuote, QuoteRev, ProcessNum, Descr, Parameter)
		VALUES (@QuoteType, @CodQuote, @QuoteRev, '01', 'TipoDies', @strTemp) 

		SET @strTemp = dbo.f_getSubstring(@CodDiesGroup, '-', 2) 
		INSERT INTO #QuoteParam(QuoteType, CodQuote, QuoteRev, ProcessNum, Descr, Parameter)
		VALUES (@QuoteType, @CodQuote, @QuoteRev, '01', 'DiamDies', @strTemp)
        
		SET @strTemp = dbo.f_getSubstring(@CodDiesGroup, '-', 3)
		INSERT INTO #QuoteParam(QuoteType, CodQuote, QuoteRev, ProcessNum, Descr, Parameter)
		VALUES (@QuoteType, @CodQuote, @QuoteRev, '01', 'HoleNumDies', @strTemp)

		INSERT INTO #QuoteParam(QuoteType, CodQuote, QuoteRev, ProcessNum, Descr, Parameter)
		SELECT	@QuoteType, @CodQuote, @QuoteRev, '01', 'NumDiesInList', COUNT(CodDies)
		FROM	dbo.DiesDet
		WHERE	CodDiesGroup = @CodDiesGroup AND CodItem = @CodItem

		INSERT INTO #QuoteParam(QuoteType, CodQuote, QuoteRev, ProcessNum, Descr, Parameter)
		SELECT	@QuoteType, @CodQuote, @QuoteRev, '01', 'NumDiesExaust', COUNT(CodDies)
		FROM	dbo.DiesDet
		WHERE	CodDiesGroup = @CodDiesGroup AND Active = 0
			
		-- inserisco parametri calcolati x lavorazione estruzione
		INSERT INTO #QuoteParam(QuoteType, CodQuote, QuoteRev, ProcessNum, Descr, Parameter)
		VALUES ( @QuoteType, @CodQuote, @QuoteRev, '01',  'CodPlant'  , @CodPlant )
               ,( @QuoteType, @CodQuote, @QuoteRev, '01', 'KeyAM'     , @KeyAM   )
               ,( @QuoteType, @CodQuote, @QuoteRev, '01', 'KeyAMIL'   , @KeyAMIL )
               ,( @QuoteType, @CodQuote, @QuoteRev, '01', 'NumSMED'   , CONVERT(NVARCHAR(50) , @NumSMED ) )
               ,( @QuoteType, @CodQuote, @QuoteRev, '01', 'KgTeo'     , CONVERT(NVARCHAR(50) , @KgTeo ) )

		--INSERT INTO #QuoteParam(QuoteType, CodQuote, QuoteRev, ProcessNum, Descr, Parameter)
		--SELECT	@QuoteType, @CodQuote, @QuoteRev, '01', 'KeyAM', @KeyAM
		--INSERT INTO #QuoteParam(QuoteType, CodQuote, QuoteRev, ProcessNum, Descr, Parameter)
		--SELECT	@QuoteType, @CodQuote, @QuoteRev, '01', 'KeyAMIL', @KeyAMIL
		--INSERT INTO #QuoteParam(QuoteType, CodQuote, QuoteRev, ProcessNum, Descr, Parameter)
		--SELECT	@QuoteType, @CodQuote, @QuoteRev, '01', 'NumSMED', @NumSMED
		--INSERT INTO #QuoteParam(QuoteType, CodQuote, QuoteRev, ProcessNum, Descr, Parameter)
		--SELECT	@QuoteType, @CodQuote, @QuoteRev, '01', 'KgTeo', @KgTeo

		-- inserisco lavorazione estrusione!
		INSERT INTO #QuoteWorkInt (QuoteType, CodQuote, QuoteRev, ProcessNum, CodPlant, Class01, Class02, Class03, NetProd, WSR)
		SELECT	@QuoteType, @CodQuote, @QuoteRev, '01', @CodPlant, @KeyAM, @KeyAMIL, @RawMat, @ProdTeo, @ScTec

		INSERT INTO #QuoteParam (QuoteType, CodQuote, QuoteRev, ProcessNum, Descr, Parameter)
		SELECT	@QuoteType, @CodQuote, @QuoteRev, '01', 'KgProdotti', SUM(KgTeo)
		FROM	dbo.QuoteList ql 
		INNER JOIN dbo.TabProdSc tps ON ql.KeyAM = tps.KeyAM
		WHERE	ql.QuoteType	= @QuoteType
			AND	ql.CodQuote		= @CodQuote
			AND	ql.QuoteRev		= @QuoteRev
			
		-- inserisco dati mancanti di MSR/CSR (scarto cesoia x estrusione) - DSR è NULLO x estrusione!
		UPDATE	#QuoteWorkInt
		SET     MSR = rmd.CSR
		FROM	#QuoteWorkInt qwi
		INNER JOIN dbo.RawMatDet rmd ON qwi.Class03 = rmd.RawMat

		-- calcolo i costi legati alla fase estrusione!
		UPDATE	#QuoteWorkInt
		SET		FC4UG = (cp.FC * cp.QuotaPlantStd / cp.QuotaManStd) / qwi.NetProd
			  , VC4UG = (cp.VC * cp.QuotaPlantStd / cp.QuotaManStd) / qwi.NetProd
			  , OH4UG = (cp.OH * cp.QuotaPlantStd / cp.QuotaManStd) / qwi.NetProd
			  , SC4UG = cp.SC / ql.BatchQty
		FROM	#QuoteWorkInt qwi
		INNER JOIN dbo.Cost2Plant cp ON qwi.CodPlant = cp.CodPlant AND qwi.ProcessNum = cp.ProcessNum
		INNER JOIN dbo.QuoteList ql ON qwi.QuoteType = ql.QuoteType AND qwi.CodQuote = ql.CodQuote AND qwi.QuoteRev = ql.QuoteRev
        WHERE	qwi.ProcessNum = '01'

		-- inserisco lavorazione incestatura!
		INSERT INTO #QuoteWorkInt (QuoteType, CodQuote, QuoteRev, ProcessNum, CodPlant, Class01, Class02, Class03)
		SELECT	@QuoteType, @CodQuote, @QuoteRev, '02', @CodPlant, @KeyAM, @KeyAMI, @RawMat
		
		-- inserisco dati mancanti di DSR x incestatura come 1 - OUT/IN
		UPDATE	#QuoteWorkInt
		SET		DSR = 1 - CAST(td.TotOUT AS DECIMAL(18,6))/CAST(td.TotIN AS DECIMAL(18,6))
		FROM	#QuoteWorkInt qwi
		INNER JOIN dbo.TabDifett td ON qwi.Class02 = td.KeyAMI AND qwi.ProcessNum = td.ProcessNum
		WHERE	qwi.ProcessNum = '02' -- solo incestatura
		
		-- inserisco lavorazione FORNO!
		INSERT INTO #QuoteWorkInt(QuoteType, CodQuote, QuoteRev, ProcessNum, CodPlant, Class01, Class02, Class03)
		SELECT	@QuoteType, @CodQuote, @QuoteRev, '03', @CodPlant, @KeyAM, @KeyAMI, @RawMat
		
		-- inserisco lavorazione imballo!
		INSERT INTO #QuoteWorkInt(QuoteType, CodQuote, QuoteRev, ProcessNum, CodPlant, Class01, Class02, Class03, Class04, Class05)
		SELECT	@QuoteType, @CodQuote, @QuoteRev, '04', @CodPlant, @KeyAM, @KeyAMIL, @RawMat, @CodItem, @KeyAMI

		-- calcolo produttività netta nella fase imballo
--		UPDATE	qwi
--		SET		NetProd = CASE ti.Durata WHEN 0 THEN 0 ELSE ti.TotOut / ti.Durata END
--		FROM	#QuoteWorkInt qwi
--		INNER JOIN dbo.TabImbArt ti ON qwi.Class04 = ti.KeyA
--      WHERE	qwi.ProcessNum = '04' -- solo imballo

		UPDATE	qwi
		SET		NetProd = CASE @PDurata WHEN 0 THEN 0 ELSE @PTotQta / @PDurata END
		FROM	#QuoteWorkInt AS qwi
--		INNER JOIN dbo.TabImbArt ti ON qwi.Class04 = ti.KeyA
        WHERE	qwi.ProcessNum = '04' -- solo imballo

        -- ADESSO LO FACCIO GIA' NELLA FUNZIONE DI RECUPERO DATI PACKAGE f_getDataCodPackag
        ---- Se Produttività netta ancora = 0 la leggo nella tabella Gruppo Imballo ( Packaging )
        --IF ( SELECT NetProd FROM #QuoteWorkInt WHERE ProcessNum = '04' ) = 0
        --  BEGIN
        --    UPDATE	qwi
        --    SET		NetProd = CASE ti.Durata WHEN 0 THEN 0 ELSE ti.TotOut / ti.Durata END
        --    FROM	#QuoteWorkInt qwi
        --    INNER JOIN dbo.TabImbGrp ti ON ti.CodPackag = @CodPackag   -- packag generico dell' offerta
        --    WHERE	qwi.ProcessNum = '04' -- solo imballo
        --  END

		-- salvo numero imballatori
		--SELECT	@NumImb = ISNULL(NumImb,0)
		--FROM	dbo.TabImbArt
		--WHERE	KeyA = @CodItem

		-- parametro num imballatori
		INSERT INTO #QuoteParam(QuoteType, CodQuote, QuoteRev, ProcessNum, Descr, Parameter)
		SELECT	@QuoteType, @CodQuote, @QuoteRev, '04', 'QuotaMan', @NumImb
		
		-- parametro Livello search package/imballo
		INSERT INTO #QuoteParam(QuoteType, CodQuote, QuoteRev, ProcessNum, Descr, Parameter)
		SELECT	@QuoteType, @CodQuote, @QuoteRev, '04', 'LivPackage', @PLiv

		-- parametro Livello search package/imballo
		INSERT INTO #QuoteParam(QuoteType, CodQuote, QuoteRev, ProcessNum, Descr, Parameter)
		SELECT	@QuoteType, @CodQuote, @QuoteRev, '04', 'LivPackageDett', @PLivDett

		-- calcolo i costi legati alla fase di imballo!
		UPDATE	#QuoteWorkInt
		SET		FC4UG = ( ( cp.FC * cp.QuotaPlantStd ) * ( @NumImb / cp.QuotaManStd ) ) / qwi.NetProd
			  , VC4UG = ( ( cp.VC * cp.QuotaPlantStd ) * ( @NumImb / cp.QuotaManStd ) ) / qwi.NetProd
			  , OH4UG = ( ( cp.OH * cp.QuotaPlantStd ) * ( @NumImb / cp.QuotaManStd ) ) / qwi.NetProd
			  , SC4UG = cp.SC / ql.BatchQty
		FROM	#QuoteWorkInt qwi
		INNER JOIN dbo.Cost2Plant cp ON qwi.CodPlant = cp.CodPlant AND qwi.ProcessNum = cp.ProcessNum
		INNER JOIN dbo.QuoteList ql ON qwi.QuoteType = ql.QuoteType AND qwi.CodQuote = ql.CodQuote AND qwi.QuoteRev = ql.QuoteRev
		WHERE	qwi.ProcessNum = '04' -- solo imballo

		-- inserisco dati mancanti di DSR x imballo come 1 - OUT/IN
		UPDATE	qwi
		SET		DSR = 1 - CAST(td.TotOUT AS DECIMAL(18,6))/CAST(td.TotIN AS DECIMAL(18,6))
		FROM	#QuoteWorkInt qwi
		INNER JOIN dbo.TabDifett td ON qwi.Class05 = td.KeyAMI AND qwi.ProcessNum = td.ProcessNum 
		WHERE	qwi.ProcessNum = '04' -- solo imballo
		
		-- recupero le MAC fase 01
		SELECT	 @MAC_SC	= MCR
				,@MAC_ST	= WCR
		FROM	#QuoteWorkInt
		WHERE	ProcessNum = '01'

		-- recupero le MAC fase 02
		SELECT	@MAC_IN		= DCR
		FROM	#QuoteWorkInt
		WHERE   ProcessNum = '02'

		-- recupero le MAC fase 04
		SELECT	@MAC_IM		= DCR
		FROM	#QuoteWorkInt
		WHERE	ProcessNum = '04'
		
		-- calcolo percentuale vendita rottame
		SELECT	@SSR = SSR
		FROM	dbo.RawMatDet
		WHERE	RawMat = @RawMat
				

        -- NOTA :   la transazione posso probabilmente iniziarla qui visto che è il 
        --          primo Update/insert/delete su tabelle non temporanee

		-- update rese RawMat!
		UPDATE	dbo.QuoteRM
		SET		FCR = @MAC_SC * @MAC_ST * @MAC_IN * @MAC_IM
		WHERE	QuoteType	= @QuoteType
			AND	CodQuote	= @CodQuote
			AND	QuoteRev	= @QuoteRev
			AND	RawMat		= @RawMat

		-- inserisco i costi delle utilities in QuoteOC
			
		-- inserisco altri costi x lavorazione estrusione! GAS ed EE
		INSERT INTO #QuoteOC(QuoteType, CodQuote, QuoteRev, ProcessNum, CodPlant, Class01, Class02, TotQty, TotCost, Quota)
		SELECT	@QuoteType, @CodQuote, @QuoteRev, '01', @CodPlant, CodUtil, @RawMat, @BatchQty, UnitCost * @BatchQty, 1
		FROM	dbo.Utilities
		WHERE	CodPlant = @CodPlant
		

		/*************************************************************
		* MATRICE
		*
		* calcolo prezzo e durata matrice con procedura a 5 step...
		* A) media ponderata prezzo ed ExpLife da DiesDet selezionando x CodItem + CodDiesGroup 
		* B) EOLLife x media ponderata su DiesDet dove Active = 0 e vita cmq superiore 5000 KG ( escludendo rotture accidentali )
		* C) SE prezzo = 0 --> prendo prezzo da DiesGroupDet selezionando x CodDiesGroup
		* D) Se EOL = 0 --> prendo ExpLife della singola matrice, se è 0 --> prendo EOLLife da DiesGroupDet selezionando x CodDiesGroup
		* E) Calcolo Price / Life
		*
		*************************************************************/

		-- (A) da DiesDet
		SELECT	@DiesPrice		= SUM(ISNULL(Price, 0)   * ISNULL(ActLife, 1)) / SUM(ISNULL(ActLife, 1)), 
				@DiesExpLife	= SUM(ISNULL(ExpLife, 0) * ISNULL(ActLife, 1)) / SUM(ISNULL(ActLife, 1))
		FROM	dbo.DiesDet
		WHERE	CodItem			= @CodItem 
			AND	CodDiesGroup	= @CodDiesGroup
		GROUP BY CodItem, CodDiesGroup

		-- (B) da DiesDet
		SELECT	@DiesEOLife		= AVG(ISNULL(ActLife, 0))
		FROM	dbo.DiesDet
		WHERE	CodItem			= @CodItem 
			AND	CodDiesGroup	= @CodDiesGroup
			AND	Active			= 0              -- solo matrici rottamate
            AND ActLife         > 5000           -- solo se hanno Life > 5000 Kg ( non rotture accidentali )
		GROUP BY CodItem, CodDiesGroup
		
		SET	@DiesPrice		= ISNULL(@DiesPrice,0)
		SET	@DiesExpLife	= ISNULL(@DiesExpLife,0)
		SET	@DiesEOLife		= ISNULL(@DiesEOLife,0)

		-- (C) verifico se prezzo è OK...
		IF (@DiesPrice = 0)
		BEGIN
			-- calcolo da DiesGroupDet
			SELECT	@DiesPrice		= ISNULL(Price, 0)
			FROM	dbo.DiesGroupDet
			WHERE	CodDiesGroup	= @CodDiesGroup
		END
		
		-- (D) verifico se vita è OK...
		IF (@DiesEOLife = 0)
		BEGIN
			-- uso exp life articolo...
			SET	@DiesEOLife = @DiesExpLife
		END
		-- controllo che non sia nulla/vuota la durata...
		IF (@DiesEOLife = 0)
		BEGIN
			SELECT	@DiesEOLife = CASE WHEN EOLLife > 0 THEN EOLLife ELSE ExpLife END
			FROM	DiesGroupDet
			WHERE	CodDiesGroup	= @CodDiesGroup
		END

		-- controllo che non sia nulla/vuota la durata...
		IF ( @DiesEOLife = 0)
		BEGIN
			SET	@DiesEOLife = 1 -- metto 1 kg che è sbagliato e mi fa esplodere prezzo matrice ma non blocca calcoli
		END

		-- (E) Calcolo price/life!
		SET	@DiesPriceLife = @DiesPrice / @DiesEOLife
		
		-- (D) verifico se vita è OK...
		IF (@DiesPriceLife = 0)
		BEGIN
			SET @DiesPriceLife = 1
			SET @valid = 0
		END
		
		-- inserisco costi per Matrice: costo e durata da matrice, se non ci sono da gruppo, (anche solo uno dei due, ovviamente più facile trovare durata x matrice...)
		INSERT INTO #QuoteOC(QuoteType, CodQuote, QuoteRev, ProcessNum, CodPlant, Class01, Class02, TotQty, TotCost, Quota, valid)
		SELECT	@QuoteType, @CodQuote, @QuoteRev, '01', @CodPlant, 'MATRICE', @RawMat, @BatchQty, @DiesPriceLife * @BatchQty, 1, @valid
		

		-- inserisco parametri calcolati x matrice
		INSERT INTO #QuoteParam(QuoteType, CodQuote, QuoteRev, ProcessNum, Descr, Parameter)
		SELECT	@QuoteType, @CodQuote, @QuoteRev, '01', 'DiesPrice', @DiesPrice

		INSERT INTO #QuoteParam(QuoteType, CodQuote, QuoteRev, ProcessNum, Descr, Parameter)
		SELECT	@QuoteType, @CodQuote, @QuoteRev, '01', 'DiesExpLife', @DiesExpLife

		INSERT INTO #QuoteParam(QuoteType, CodQuote, QuoteRev, ProcessNum, Descr, Parameter)
		SELECT	@QuoteType, @CodQuote, @QuoteRev, '01', 'DiesEOLife', @DiesEOLife

		/*************************************************************
		* VENDITA ROTTAME
		*
		* calcolo COSTO DI VENDITA PER LE 2 FASI ESTRUSIONE 01 ED IMBALLO 04
		* - calcolo costi variabili fase 01 / 04
		* - calcolo costo di vendita x fase 01 / 04
		*************************************************************/

		SELECT	@OCF01 = SUM(ISNULL(C4UG,0))
		FROM	#QuoteOC
			
		SELECT	@VCF01 = @OCF01 + VC4UG	
		FROM	#QuoteWorkInt
		WHERE	ProcessNum	= '01'
			
		SELECT	@VCF04 = @OCF01 + SUM(VC4UG)
		FROM	#QuoteWorkInt
			
		SELECT	@SellCostF01 = ((@MAC_ST * @MAC_SC * @MAC_IN) - 1) * (q.RawMatCost  + q.RawMatExtraCost - CASE WHEN SSVA > 0 THEN SSVA ELSE q.RawMatCost * SSVR END + @VCF01) -- ((prodotto delle MAC = inverso del prodotto delle rese) - 1) * (costo Al - prezzo rivendita + costi var fase 01)
			  , @RefCostF01  = -- ( (A - B) / 100 - C )
							   (
								-- (A) = (costo pieno di acquisto + costi fase 1) * MAC * 100 (IN CENTESIMI)
							   	((q.RawMatCost + q.RawMatExtraCost + @VCF01) * (@MAC_ST * @MAC_SC * @MAC_IN * 100))
								-- (B) = ((MAC * 100) - 100) * Resa di fonderia * (costo pieno acquisto - costo di trasformazione))
							  -	((@MAC_ST * @MAC_SC * @MAC_IN * 100) - 100) * rmd.ProcYield * (q.RawMatCost + q.RawMatExtraCost + @VCF01 - rmd.ProcCost)
							   ) / 100 -- divido per 100 finale
							    -- (C) = sottraggo costo pieno alluminio
							  - (q.RawMatCost + q.RawMatExtraCost + @VCF01)
		FROM	dbo.RawMatDet rmd 
		INNER JOIN dbo.QuoteRM q ON q.RawMat = rmd.RawMat
		WHERE	q.QuoteType	= @QuoteType
			AND	q.CodQuote	= @CodQuote
			AND	q.QuoteRev	= @QuoteRev
			AND	q.RawMat	= @RawMat
			
		SELECT	@SellCostF04 = ((@MAC_IM) - 1) * (q.RawMatCost  + q.RawMatExtraCost - CASE WHEN SSVA > 0 THEN SSVA ELSE q.RawMatCost * SSVR END + @VCF01 + @VCF04) -- ((prodotto delle MAC = inverso del prodotto delle rese) - 1) * (costo Al - prezzo rivendita + costi var fase 04)
			  , @RefCostF04  = -- ( (A - B) / 100 - C )
							   (
								-- (A) = (costo pieno di acquisto + costi variabili fase 1 e 4) * MAC * 100 (IN CENTESIMI)
							   	((q.RawMatCost + q.RawMatExtraCost + @VCF01 + @VCF04) * (@MAC_IM * 100))
								-- (B) = ((MAC * 100) - 100) * Resa di fonderia * (costo pieno acquisto - costo di trasformazione))
							  -	((@MAC_IM * 100) - 100) * rmd.ProcYield * (q.RawMatCost + q.RawMatExtraCost + @VCF01 + @VCF04 - rmd.ProcCost)
							   ) / 100 -- divido per 100 finale
							    -- (C) = sottraggo costo pieno alluminio
							  - (q.RawMatCost + q.RawMatExtraCost + @VCF01 + @VCF04)

							  -- NOTA: usiamo (q.RawMatCost + q.RawMatExtraCost + @VCF01) e non (q.RawMatCost + q.RawMatExtraCost + @VCF01 + @RefCostF01) perché la differenza è minimale, si tratta di 10/20 PPM...

		FROM	dbo.RawMatDet rmd 
        INNER JOIN dbo.QuoteRM q ON q.RawMat = rmd.RawMat
		WHERE	q.QuoteType	= @QuoteType
			AND	q.CodQuote	= @CodQuote
			AND	q.QuoteRev	= @QuoteRev
			AND	q.RawMat	= @RawMat
		
		-- inserisco costi per VENDITA
		INSERT INTO #QuoteOC(QuoteType, CodQuote, QuoteRev, ProcessNum, CodPlant, Class01, Class02, TotQty, TotCost, Quota)
		SELECT	@QuoteType, @CodQuote, @QuoteRev, '01', @CodPlant, 'VENDITA', @RawMat, @BatchQty, @SellCostF01 * @BatchQty, @SSR

		-- inserisco costi per ROTTAME
		INSERT INTO #QuoteOC(QuoteType, CodQuote, QuoteRev, ProcessNum, CodPlant, Class01,  Class02, TotQty, TotCost, Quota)
		SELECT	@QuoteType, @CodQuote, @QuoteRev, '01', @CodPlant, 'ROTTAME', @RawMat, @BatchQty, @RefCostF01 * @BatchQty, 1 - @SSR
		
		-- inserisco costi per VENDITA
		INSERT INTO #QuoteOC(QuoteType, CodQuote, QuoteRev, ProcessNum, CodPlant, Class01, Class02, TotQty, TotCost, Quota)
		SELECT	@QuoteType, @CodQuote, @QuoteRev, '04', @CodPlant, 'VENDITA', @RawMat, @BatchQty, @SellCostF04 * @BatchQty, @SSR

		-- inserisco costi per ROTTAME
		INSERT INTO #QuoteOC(QuoteType, CodQuote, QuoteRev, ProcessNum, CodPlant, Class01,  Class02, TotQty, TotCost, Quota)
		SELECT	@QuoteType, @CodQuote, @QuoteRev, '04', @CodPlant, 'ROTTAME', @RawMat, @BatchQty, @RefCostF04 * @BatchQty, 1 - @SSR
	
	    -- calcolo Package Cost e RMWeight da tab PackageDet
        -- EXEC stp_packageCost @CodItem, @CodClient, @CodPackag, @PDesc=@PkgDesc OUTPUT, @RMWeight=@PRMWeight OUTPUT, @Weight=@PWeight OUTPUT, @Tare=@PTare OUTPUT, @PackCost=@PCost OUTPUT, @TareStRat=@PTareStRatio OUTPUT
        -- stored sostituita perchè la maggior parte dei calcoli li ho già fatti
	    SELECT	@PCost          = RMCost / @PWeight 
              , @PRMWeight      = RMWeight
              , @PkgDesc        = PackagDesc
              , @PTareStRatio   = ( RMWeight - @PTare) / @PWeight
	    FROM	dbo.PackagDet
	    WHERE	CodPackag = @CodPackag

		-- inserisco costi per IMBALLO
		INSERT INTO #QuoteOC(QuoteType, CodQuote, QuoteRev, ProcessNum, CodPlant, Class01,  Class02, TotQty, TotCost, Quota)
		SELECT	@QuoteType, @CodQuote, @QuoteRev, '04', @CodPlant, 'IMBALLO', @RawMat, @BatchQty, @PCost * @BatchQty, 1


		-- inserisco parametri calcolati x imballaggio
		INSERT INTO #QuoteParam(QuoteType, CodQuote, QuoteRev, ProcessNum, Descr, Parameter)
		SELECT	@QuoteType, @CodQuote, @QuoteRev, '04', 'PkgDesc', @PkgDesc

		INSERT INTO #QuoteParam(QuoteType, CodQuote, QuoteRev, ProcessNum, Descr, Parameter)
		SELECT	@QuoteType, @CodQuote, @QuoteRev, '04', 'PRMWeight', @PRMWeight

		INSERT INTO #QuoteParam(QuoteType, CodQuote, QuoteRev, ProcessNum, Descr, Parameter)
		SELECT	@QuoteType, @CodQuote, @QuoteRev, '04', 'PWeight', @PWeight

		INSERT INTO #QuoteParam(QuoteType, CodQuote, QuoteRev, ProcessNum, Descr, Parameter)
		SELECT	@QuoteType, @CodQuote, @QuoteRev, '04', 'PTare', @PTare

		INSERT INTO #QuoteParam(QuoteType, CodQuote, QuoteRev, ProcessNum, Descr, Parameter)
		SELECT	@QuoteType, @CodQuote, @QuoteRev, '04', 'TareStRatio', @PTareStRatio
		
		
		---------------------------------------------	
		-- inserisco costi per TRASPORTI
		---------------------------------------------
		-- recupero zona da cliente...
		SELECT	@TranspZone = TranspZone
		FROM	dbo.ClientDet	
		WHERE	CodClient	= @CodClient

		-- recupero tipo di trasporto
		SELECT	@HasTC = ISNULL(i.HasTC, 0)
		FROM	dbo.QuoteList q INNER JOIN Incoterms i ON q.CodInco = i.CodInco
		WHERE	q.QuoteType	= @QuoteType
			AND	q.CodQuote	= @CodQuote
			AND	q.QuoteRev	= @QuoteRev

		-- recupero costi trasporto
		SELECT	@TranspCost = TranspCost
		FROM	dbo.TranspCostDet
		WHERE	TranspZone	= @TranspZone

		INSERT INTO #QuoteOC(QuoteType, CodQuote, QuoteRev, ProcessNum, CodPlant, Class01,  Class02, TotQty, TotCost, Quota)
		SELECT	@QuoteType, @CodQuote, @QuoteRev, '04', @CodPlant, 'TRASPORTI', @RawMat, @BatchQty, @HasTC * @TranspCost * @BatchQty, 1

		
		---------------------------------------------	
		-- inserisco costi per PROVVIGIONI
		---------------------------------------------
		SELECT	@Provvig = ISNULL(a.QuotaProvvAg, 0)
		FROM	dbo.AgentsDet a
		INNER JOIN ClientDet c ON a.CodAg = c.CodAg
		INNER JOIN QuoteList q ON q.CodClient = c.CodClient
		WHERE	q.QuoteType	= @QuoteType
			AND	q.CodQuote	= @CodQuote
			AND	q.QuoteRev	= @QuoteRev

		-- inserisco costi per PROVVIGIONI
		INSERT INTO #QuoteOC(QuoteType, CodQuote, QuoteRev, ProcessNum, CodPlant, Class01,  Class02, TotQty, TotCost, Quota)
		SELECT	@QuoteType, @CodQuote, @QuoteRev, '04', @CodPlant, 'PROVVIGIONI', @RawMat, @BatchQty, @Provvig * @BatchQty, 1

        /* ==================================================
             CARICO TABELLE EFFETTIVE
           ==================================================*/

		-- carico quote parametri!
		INSERT dbo.QuoteParam
		SELECT * FROM #QuoteParam

		-- carico lavorazioni INTERNE!
		INSERT dbo.QuoteWorkInt  -- ci sono valori calcolati quindi devo selezionare i campi
		SELECT QuoteType, CodQuote, QuoteRev, NumWI, ProcessNum, CodPlant, Class01, Class02, Class03, Class04, Class05
             , NetProd, WSR, MSR, DSR, FC4UG, VC4UG, OH4UG, SC4UG, valid 
        FROM #QuoteWorkInt

		-- carico OTHERCOSTS
		INSERT dbo.QuoteOC  -- ci sono valori calcolati quindi devo selezionare i campi
		SELECT QuoteType, CodQuote, QuoteRev, NumEx, ProcessNum, CodPlant, Class01, Class02, Class03, Class04
             , Class05, TotQty, TotCost, Quota, valid
        FROM #QuoteOC


	COMMIT TRAN
	
	--SELECT * FROM #QuoteParam
	--SELECT * FROM #QuoteWorkInt
	--SELECT * FROM #QuoteOC

	-- elimino temp table...
	IF OBJECT_ID('tempdb..#QuoteParam') IS NOT NULL
		DROP TABLE #QuoteParam
    IF OBJECT_ID('tempdb..#QuoteWorkInt') IS NOT NULL
		DROP TABLE #QuoteWorkInt
    IF OBJECT_ID('tempdb..#QuoteOC') IS NOT NULL
		DROP TABLE #QuoteOC

END
GO
PRINT N'Creating [dbo].[stp_QL_fullDataAll]...';


GO
-- =============================================
-- STORED PROCEDURE stp_QL_fullDataAll
--
-- Author:		Steamware
-- Create date: 2014.02.07
-- Description:	Recupera tutti i dati di tutte le offerte salvate
-- =============================================
CREATE PROCEDURE dbo.stp_QL_fullDataAll

AS
SELECT *
FROM v_QuoteFull_Q
ORDER BY CodQuote DESC

RETURN
GO
PRINT N'Creating [dbo].[stp_QL_update_30_01]...';


GO

-- =============================================
-- Author:		Steamware
-- Create date: 2014.01.22
-- Description:	aggiorna le tabelle QuoteList con i dati selezionati dalla TabProdSc
-- =============================================
CREATE PROCEDURE [dbo].[stp_QL_update_30_01]
(
	@QuoteType	CHAR(1) = 'Q',
	@CodQuote	BIGINT	= 0,
	@QuoteRev	INT		= 0
) 
AS
BEGIN

    SET NOCOUNT ON;

	-- dichiaro valori da recuperare
	DECLARE	@strTemp		NVARCHAR(50) = '' --stringa temporanea x variabili "locali"

	DECLARE @valid			BIT
	DECLARE @CodDiesGroup	NVARCHAR(50)
	DECLARE @CodPlant		NVARCHAR(50)
	DECLARE @CodPlantFix	NVARCHAR(50) = ''
	DECLARE @HoleNum		INT
	DECLARE @CodItem		NVARCHAR(50) = '' --cod item
	DECLARE @ItemDescr		NVARCHAR(50) = '' -- descrizione item
	DECLARE @KeyAM			NVARCHAR(50) = ''
	DECLARE @KeyAMI			NVARCHAR(50) = ''
	DECLARE @KeyAMIL		NVARCHAR(50) = ''
	DECLARE @NumSMED		INT = 0 -- numero cambi
	DECLARE @KgTeo			DECIMAL(18, 6) = 0 -- kg totali
	DECLARE @RawMat			NVARCHAR(50)
	DECLARE	@ProdTeo		DECIMAL(18,6)
	DECLARE	@ScTec			DECIMAL(18,6)
	DECLARE	@BatchQty		INT
	DECLARE	@MAC_SC			DECIMAL(18,6) -- Messa a cento scarto cesoia
	DECLARE	@MAC_ST			DECIMAL(18,6) -- Messa a cento scarto tecnico
	DECLARE	@MAC_IN			DECIMAL(18,6) -- Messa a cento difettosità all'incestatura
	DECLARE	@MAC_IM			DECIMAL(18,6) -- Messa a cento difettosità all'imballo
	DECLARE	@SSR			DECIMAL(9,6) -- percentuale vendita rottame
	DECLARE	@DiesPrice		DECIMAL(9,3) -- prezzo matrice
	DECLARE	@DiesEOLife		DECIMAL(9,2) -- durata matrice
	DECLARE	@DiesExpLife	DECIMAL(9,2) -- durata matrice
	DECLARE	@DiesPriceLife	DECIMAL(18,6) -- Price/Life matrice
	DECLARE	@OCF01			DECIMAL(18,6) = 0 -- altri costi di fase 01
	DECLARE	@VCF01			DECIMAL(18,6) = 0 -- costi variabili di fase 01
	DECLARE	@VCF04			DECIMAL(18,6) = 0 -- costi variabili di fase 04
	DECLARE	@SellCostF01	DECIMAL(18,6) = 0 -- costo vendita fase 01
	DECLARE	@SellCostF04	DECIMAL(18,6) = 0 -- costo vendita fase 04
	DECLARE	@RefCostF01		DECIMAL(18,6) = 0 -- costo rifusione fase 01 
	DECLARE	@RefCostF04		DECIMAL(18,6) = 0 -- costo rifusione fase 04
	-- IMBALLO
	DECLARE	@CodPackag		NVARCHAR(50) = '0' -- codice dell'imballo
	DECLARE @CodClient		NVARCHAR(50) = '' -- codice cliente
	DECLARE @NumImb			DECIMAL(9,6) = 0 -- num imballatori
	DECLARE @PkgDesc		NVARCHAR(50) = '' -- descrizione imballo
	DECLARE @PRMWeight		DECIMAL(9,4) = 0 -- peso dell'imballo
	DECLARE @PWeight		DECIMAL(9,4) = 0 -- peso del pacco
	DECLARE @PTare			DECIMAL(9,4) = 0 -- media delal tara di imballo dichiarata
	DECLARE @PCost			DECIMAL(9,6) = 0 -- costo unitario dell'imballo (al kg) 
	DECLARE @PTareStRatio	DECIMAL(9,4) = 0 -- coefficiente di recupero tara/prodotto

	-- TRASPORTI
	DECLARE	@TranspZone		NVARCHAR(50) = '', -- codice ZONA
			@TranspCost		DECIMAL(9,6), -- costo di trasporto
			@HasTC			INT

	-- PROVVIGIONI
	DECLARE	@Provvig		DECIMAL(9,6) -- provvigione agente

	-- default: validità è true!
	SET		@valid = 1

    -- =================================================
    --   CREAZIONE TEMP TABLE
    -- =================================================

	-- elimino e ricreo #QuoteParam temp table...
	IF OBJECT_ID('tempdb..#QuoteParam') IS NOT NULL
		DROP TABLE #QuoteParam

	CREATE TABLE #QuoteParam
	(
		[QuoteType] [char](1) NOT NULL,
		[CodQuote] [bigint] NOT NULL,
		[QuoteRev] [int] NOT NULL,
		[NumP] [int] IDENTITY(1,1) NOT NULL,
		[ProcessNum] [nvarchar](50) NOT NULL,
		[Descr] [nvarchar](50) NOT NULL,
		[Parameter] [nvarchar](100) NOT NULL,
	--PRIMARY KEY
	--		(	[NumP] ASC, [QuoteType] ASC, [CodQuote] ASC, [QuoteRev] ASC ) WITH  (PAD_INDEX  = ON, FILLFACTOR = 90 )
	 )

	-- elimino e ricreo #QuoteParam temp table...
	IF OBJECT_ID('tempdb..#QuoteWorkInt') IS NOT NULL
		DROP TABLE #QuoteWorkInt

   CREATE TABLE #QuoteWorkInt
    (
        [QuoteType]     [char](1) NOT NULL,
        [CodQuote]      [bigint] NOT NULL,
        [QuoteRev]      [int] NOT NULL,
        [NumWI]         [int] IDENTITY(1,1) NOT NULL,
        [ProcessNum]    [nvarchar](50) NOT NULL,
        [CodPlant]      [nvarchar](50) NOT NULL,
        [Class01]       [nvarchar](50) NOT NULL DEFAULT (''),
        [Class02]       [nvarchar](50) NOT NULL DEFAULT (''),
        [Class03]       [nvarchar](50) NOT NULL DEFAULT (''),
        [Class04]       [nvarchar](50) NOT NULL DEFAULT (''),
        [Class05]       [nvarchar](50) NOT NULL DEFAULT (''),
        [NetProd]       [decimal](9, 3) NOT NULL DEFAULT ((0)),
        [WSR]           [decimal](9, 8) NOT NULL DEFAULT ((0)),
        [MSR]           [decimal](9, 8) NOT NULL DEFAULT ((0)),
        [DSR]           [decimal](9, 8) NOT NULL DEFAULT ((0)),
        [FC4UG]         [decimal](9, 6) NOT NULL DEFAULT ((0)),
        [VC4UG]         [decimal](9, 6) NOT NULL DEFAULT ((0)),
        [OH4UG]         [decimal](9, 6) NOT NULL DEFAULT ((0)),
        [SC4UG]         [decimal](9, 6) NOT NULL DEFAULT ((0)),
        [WYR]  AS ((1)-[WSR]),
        [MYR]  AS ((1)-[MSR]),
        [DYR]  AS ((1)-[DSR]),
        [WCR]  AS ((1)/((1)-[WSR])),
        [MCR]  AS ((1)/((1)-[MSR])),
        [DCR]  AS ((1)/((1)-[DSR])),
        [valid] [bit] NOT NULL DEFAULT((1)),
    )

    -- elimino e ricreo #QuoteParam temp table...
    IF OBJECT_ID('tempdb..#QuoteOC') IS NOT NULL
		DROP TABLE #QuoteOC

    CREATE TABLE #QuoteOC 
    (
	    [QuoteType] [char](1) NOT NULL,
	    [CodQuote]  [bigint] NOT NULL,
	    [QuoteRev]  [int] NOT NULL,
	    [NumEx]     [int] IDENTITY(1,1) NOT NULL,
	    [ProcessNum] [nvarchar](50)     NOT NULL,
	    [CodPlant]  [nvarchar](50)      NOT NULL,
	    [Class01]   [nvarchar](50)      NOT NULL DEFAULT (''),
	    [Class02]   [nvarchar](50)      NOT NULL DEFAULT (''),
	    [Class03]   [nvarchar](50)      NOT NULL DEFAULT (''),
	    [Class04]   [nvarchar](50)      NOT NULL DEFAULT (''),
	    [Class05]   [nvarchar](50)      NOT NULL DEFAULT (''),
	    [TotQty]    [decimal](18, 6)    NOT NULL DEFAULT ((1)),
	    [TotCost]   [decimal](18, 6)    NOT NULL DEFAULT ((0)),
	    [Quota]     [decimal](18, 6)    NOT NULL DEFAULT ((1)),
	    [C4UG]  AS (([TotCost]*[Quota])/[TotQty]),
	    [valid]     [bit] NOT NULL DEFAULT ((1))
    )

    -- ===================================
    --  INIZIO TRANSAZIONE
    -- ===================================
	SET XACT_ABORT ON;
	BEGIN TRAN

		---------------------------------------
		-- svuotamento iniziale
		---------------------------------------
	
    	-- elimino lavorazioni esterne!
		DELETE 
		FROM	dbo.QuoteWorkExt
		WHERE	QuoteType	= @QuoteType
			AND	CodQuote	= @CodQuote
			AND	QuoteRev	= @QuoteRev

		-- se ci sono eccezioni nella tab dell'anagrafico articoli imposto il codPlant desiderato
		SET	@CodPlantFix = ISNULL ( ( SELECT id.CodPlant FROM dbo.ItemDet id INNER JOIN dbo.QuoteList ql ON id.CodItem = ql.CodItem
		                              WHERE  ql.QuoteType   = @QuoteType
			                          AND    ql.CodQuote    = @CodQuote
			                          AND    ql.QuoteRev    = @QuoteRev ), '' )

		-- recupero da dati dell'offerta il valore del cliente
		SELECT	@CodClient		= CodClient
		FROM	dbo.QuoteList
		WHERE	QuoteType		= @QuoteType
			AND	CodQuote		= @CodQuote
			AND	QuoteRev		= @QuoteRev
        
		-- recupero dati!!
		SELECT	TOP 1 @CodItem	= ql.CodItem
					, @CodDiesGroup = tps.CodDiesGroup
                    , @CodPlant = CASE WHEN @CodPlantFix <> '' THEN @CodPlantFix ELSE tps.CodPlant END
					, @HoleNum  = tps.HoleNum
					, @KeyAM	= ql.KeyAM
					, @KeyAMI	= ql.KeyAM + '-' + ISNULL(@CodPlant,'0000')
					, @KeyAMIL	= ql.KeyAM + '-' + ISNULL(@CodPlant,'0000') + '-' + CAST(ISNULL(tps.HoleNum,0) AS NVARCHAR(10))
					, @ProdTeo	= tps.ProdTeo
					, @ScTec	= tps.ScTec
					, @KgTeo	= tps.KgTeo
					, @NumSMED	= tps.NumSMED
					, @RawMat	= ql.RawMat
					, @BatchQty	= ql.BatchQty
					, @ItemDescr= i.ItemDescr
		FROM dbo.QuoteList ql 
        INNER JOIN dbo.TabProdSc tps ON ql.KeyAM = tps.KeyAM 
        INNER JOIN dbo.ItemDet i ON ql.CodItem = i.CodItem
		WHERE	ql.QuoteType	= @QuoteType
			AND	ql.CodQuote		= @CodQuote
			AND	ql.QuoteRev		= @QuoteRev
		ORDER BY tps.KgTeo DESC
		
		-- recupero da dati dell'offerta il valore del package scelto
        SET @CodPackag = ( SELECT dbo.f_getCodPackag( @CodItem , @CodClient ) )

        -- e aggiorno QuoteRM
		UPDATE	dbo.QuoteRM
            SET CodPackag = @CodPackag
		FROM	dbo.QuoteRM
		WHERE	QuoteType		= @QuoteType
			AND	CodQuote		= @CodQuote
			AND	QuoteRev		= @QuoteRev

		INSERT INTO #QuoteParam(QuoteType, CodQuote, QuoteRev, ProcessNum, Descr, Parameter)
		VALUES (@QuoteType, @CodQuote, @QuoteRev, '01', 'ItemDescr', @ItemDescr)

		INSERT INTO #QuoteParam(QuoteType, CodQuote, QuoteRev, ProcessNum, Descr, Parameter)
		SELECT	@QuoteType, @CodQuote, @QuoteRev, '01', 'CodifProfilo', Class01
		FROM	dbo.ItemDet
		WHERE	CodItem = @CodItem

		INSERT INTO #QuoteParam(QuoteType, CodQuote, QuoteRev, ProcessNum, Descr, Parameter)
		SELECT	@QuoteType, @CodQuote, @QuoteRev, '01', 'ClasseMerc', Class02
		FROM	dbo.ItemDet
		WHERE	CodItem	= @CodItem
		
		INSERT INTO #QuoteParam(QuoteType, CodQuote, QuoteRev, ProcessNum, Descr, Parameter)
		SELECT	@QuoteType, @CodQuote, @QuoteRev, '01', 'CodClientAssoc', Class03
		FROM	dbo.ItemDet
		WHERE	CodItem	= @CodItem
        
		INSERT INTO #QuoteParam(QuoteType, CodQuote, QuoteRev, ProcessNum, Descr, Parameter)
		SELECT	@QuoteType, @CodQuote, @QuoteRev, '01', 'ClientNameAssoc', ClientDet.ClientName
		FROM	dbo.ItemDet INNER JOIN ClientDet ON ItemDet.Class03=ClientDet.CodClient
		WHERE	CodItem	= @CodItem
		
		-- INFORMAZIONI su MATRICE
		INSERT INTO #QuoteParam(QuoteType, CodQuote, QuoteRev, ProcessNum, Descr, Parameter)
		VALUES (@QuoteType, @CodQuote, @QuoteRev, '01', 'CodDiesGroup', @CodDiesGroup)

		SET @strTemp = dbo.f_getSubstring(@CodDiesGroup, '-', 1) --@strTemp = SUBSTRING(@CodDiesGroup, 0, CHARINDEX('-', @CodDiesGroup)) -- !!!fare con finc Gian
		INSERT INTO #QuoteParam(QuoteType, CodQuote, QuoteRev, ProcessNum, Descr, Parameter)
		VALUES (@QuoteType, @CodQuote, @QuoteRev, '01', 'TipoDies', @strTemp) 

		SET @strTemp = dbo.f_getSubstring(@CodDiesGroup, '-', 2) --@strTemp = SUBSTRING(REPLACE(@CodDiesGroup, @strTemp,''), 2, CHARINDEX('-', @CodDiesGroup))	 -- !!!fare con finc Gian
		INSERT INTO #QuoteParam(QuoteType, CodQuote, QuoteRev, ProcessNum, Descr, Parameter)
		VALUES (@QuoteType, @CodQuote, @QuoteRev, '01', 'DiamDies', @strTemp)
        
		SET @strTemp = dbo.f_getSubstring(@CodDiesGroup, '-', 3) --@strTemp = SUBSTRING(REPLACE(@CodDiesGroup, @strTemp,''), 5, CHARINDEX('-', @CodDiesGroup)) -- !!!fare con finc Gian	
		INSERT INTO #QuoteParam(QuoteType, CodQuote, QuoteRev, ProcessNum, Descr, Parameter)
		VALUES (@QuoteType, @CodQuote, @QuoteRev, '01', 'HoleNumDies', @strTemp)

		INSERT INTO #QuoteParam(QuoteType, CodQuote, QuoteRev, ProcessNum, Descr, Parameter)
		SELECT	@QuoteType, @CodQuote, @QuoteRev, '01', 'NumDiesInList', COUNT(CodDies)
		FROM	dbo.DiesDet
		WHERE	CodDiesGroup = @CodDiesGroup AND CodItem = @CodItem

		INSERT INTO #QuoteParam(QuoteType, CodQuote, QuoteRev, ProcessNum, Descr, Parameter)
		SELECT	@QuoteType, @CodQuote, @QuoteRev, '01', 'NumDiesExaust', COUNT(CodDies)
		FROM	dbo.DiesDet
		WHERE	CodDiesGroup = @CodDiesGroup AND Active = 0
			
		-- inserisco parametri calcolati x lavorazione estruzione
		INSERT INTO #QuoteParam(QuoteType, CodQuote, QuoteRev, ProcessNum, Descr, Parameter)
		SELECT	@QuoteType, @CodQuote, @QuoteRev, '01', 'CodPlant', @CodPlant

		INSERT INTO #QuoteParam(QuoteType, CodQuote, QuoteRev, ProcessNum, Descr, Parameter)
		SELECT	@QuoteType, @CodQuote, @QuoteRev, '01', 'KeyAM', @KeyAM

		INSERT INTO #QuoteParam(QuoteType, CodQuote, QuoteRev, ProcessNum, Descr, Parameter)
		SELECT	@QuoteType, @CodQuote, @QuoteRev, '01', 'KeyAMIL', @KeyAMIL

		INSERT INTO #QuoteParam(QuoteType, CodQuote, QuoteRev, ProcessNum, Descr, Parameter)
		SELECT	@QuoteType, @CodQuote, @QuoteRev, '01', 'NumSMED', @NumSMED

		INSERT INTO #QuoteParam(QuoteType, CodQuote, QuoteRev, ProcessNum, Descr, Parameter)
		SELECT	@QuoteType, @CodQuote, @QuoteRev, '01', 'KgTeo', @KgTeo

        -- tolto: è duplicato di HoleNumDies
		--INSERT INTO #QuoteParam(QuoteType, CodQuote, QuoteRev, ProcessNum, Descr, Parameter)
		--SELECT	@QuoteType, @CodQuote, @QuoteRev, '01', 'HoleNum', @HoleNum

		-- inserisco lavorazione estrusione!
		INSERT INTO #QuoteWorkInt (QuoteType, CodQuote, QuoteRev, ProcessNum, CodPlant, Class01, Class02, Class03, NetProd, WSR)
		SELECT	@QuoteType, @CodQuote, @QuoteRev, '01', @CodPlant, @KeyAM, @KeyAMIL, @RawMat, @ProdTeo, @ScTec

		INSERT INTO #QuoteParam (QuoteType, CodQuote, QuoteRev, ProcessNum, Descr, Parameter)
		SELECT	@QuoteType, @CodQuote, @QuoteRev, '01', 'KgProdotti', SUM(KgTeo)
		FROM	dbo.QuoteList ql 
		INNER JOIN dbo.TabProdSc tps ON ql.KeyAM = tps.KeyAM
		WHERE	ql.QuoteType	= @QuoteType
			AND	ql.CodQuote		= @CodQuote
			AND	ql.QuoteRev		= @QuoteRev
			
		--SELECT	@cont = @cont + 1
		--INSERT INTO QuoteParam(QuoteType, CodQuote, QuoteRev, NumP, ProcessNum, Descr, Parameter)
		--SELECT	@QuoteType, @CodQuote, @QuoteRev, @cont, '01', 'NumLotti', COUNT(*)
		--FROM	QuoteList ql INNER JOIN TabProdSc tps ON ql.KeyAM = tps.KeyAM
		--WHERE	ql.QuoteType	= @QuoteType
		--	AND	ql.CodQuote		= @CodQuote
		--	AND	ql.QuoteRev		= @QuoteRev

		-- inserisco dati mancanti di MSR/CSR (scarto cesoia x estrusione) - DSR è NULLO x estrusione!
		UPDATE	qwi
		SET		MSR = rmd.CSR
		FROM	#QuoteWorkInt qwi
		INNER JOIN dbo.RawMatDet rmd ON qwi.Class03 = rmd.RawMat

		-- calcolo i costi legati alla fase estrusione!
		UPDATE	qwi
		SET		FC4UG = (cp.FC * cp.QuotaPlantStd / cp.QuotaManStd) / qwi.NetProd
			  , VC4UG = (cp.VC * cp.QuotaPlantStd / cp.QuotaManStd) / qwi.NetProd
			  , OH4UG = (cp.OH * cp.QuotaPlantStd / cp.QuotaManStd) / qwi.NetProd
			  , SC4UG = cp.SC / ql.BatchQty
		FROM	#QuoteWorkInt qwi
			INNER JOIN dbo.Cost2Plant cp ON qwi.CodPlant = cp.CodPlant AND qwi.ProcessNum = cp.ProcessNum
			INNER JOIN dbo.QuoteList ql ON qwi.QuoteType = ql.QuoteType AND qwi.CodQuote = ql.CodQuote AND qwi.QuoteRev = ql.QuoteRev
        WHERE	qwi.ProcessNum = '01'

		-- inserisco lavorazione incestatura!
		INSERT INTO #QuoteWorkInt (QuoteType, CodQuote, QuoteRev, ProcessNum, CodPlant, Class01, Class02, Class03)
		SELECT	@QuoteType, @CodQuote, @QuoteRev, '02', @CodPlant, @KeyAM, @KeyAMI, @RawMat
		
		-- inserisco dati mancanti di DSR x incestatura come 1 - OUT/IN
		UPDATE	qwi
		SET		DSR = 1 - CAST(td.TotOUT AS DECIMAL(18,6))/CAST(td.TotIN AS DECIMAL(18,6))
		FROM	#QuoteWorkInt qwi
		INNER JOIN dbo.TabDifett td ON qwi.Class02 = td.KeyAMI AND qwi.ProcessNum = td.ProcessNum
		WHERE	qwi.ProcessNum = '02' -- solo incestatura
		
		-- inserisco lavorazione FORNO!
		INSERT INTO #QuoteWorkInt(QuoteType, CodQuote, QuoteRev, ProcessNum, CodPlant, Class01, Class02, Class03)
		SELECT	@QuoteType, @CodQuote, @QuoteRev, '03', @CodPlant, @KeyAM, @KeyAMI, @RawMat
		
		-- inserisco lavorazione imballo!
		INSERT INTO #QuoteWorkInt(QuoteType, CodQuote, QuoteRev, ProcessNum, CodPlant, Class01, Class02, Class03, Class04, Class05)
		SELECT	@QuoteType, @CodQuote, @QuoteRev, '04', @CodPlant, @KeyAM, @KeyAMIL, @RawMat, @CodItem, @KeyAMI

		-- calcolo produttività netta nella fase imballo
		UPDATE	qwi
		SET		NetProd = CASE ti.Durata WHEN 0 THEN 0 ELSE ti.TotOut / ti.Durata END
		FROM	#QuoteWorkInt qwi
		INNER JOIN dbo.TabImbArt ti ON qwi.Class04 = ti.KeyA
        WHERE	qwi.ProcessNum = '04' -- solo imballo

        -- Se Produttività netta ancora = 0 la leggo nella tabella Gruppo Imballo ( Packaging )
        IF ( SELECT NetProd FROM #QuoteWorkInt WHERE ProcessNum = '04' ) = 0
          BEGIN
            UPDATE	qwi
            SET		NetProd = CASE ti.Durata WHEN 0 THEN 0 ELSE ti.TotOut / ti.Durata END
            FROM	#QuoteWorkInt qwi
            INNER JOIN dbo.TabImbGrp ti ON ti.CodPackag = @CodPackag   -- packag generico dell' offerta
            WHERE	qwi.ProcessNum = '04' -- solo imballo
          END

		-- salvo numero imballatori
		SELECT	@NumImb = ISNULL(NumImb,0)
		FROM	dbo.TabImbArt
		WHERE	KeyA = @CodItem

		-- parametro num imballatori
		INSERT INTO #QuoteParam(QuoteType, CodQuote, QuoteRev, ProcessNum, Descr, Parameter)
		SELECT	@QuoteType, @CodQuote, @QuoteRev, '04', 'QuotaMan', @NumImb
		
		-- calcolo i costi legati alla fase di imballo!
        -- QUI VA FATTO CALCOLO PUNTUALE SU quotaPlant tramite Articolo-Cliente / Articolo / Packaging
		UPDATE	qwi
		SET		FC4UG = (cp.FC * cp.QuotaPlantStd / cp.QuotaManStd) / qwi.NetProd
			  , VC4UG = (cp.VC * cp.QuotaPlantStd / cp.QuotaManStd) / qwi.NetProd
			  , OH4UG = (cp.OH * cp.QuotaPlantStd / cp.QuotaManStd) / qwi.NetProd
			  , SC4UG = cp.SC / ql.BatchQty
		FROM	#QuoteWorkInt qwi
		INNER JOIN dbo.Cost2Plant cp ON qwi.CodPlant = cp.CodPlant AND qwi.ProcessNum = cp.ProcessNum
		INNER JOIN dbo.QuoteList ql ON qwi.QuoteType = ql.QuoteType AND qwi.CodQuote = ql.CodQuote AND qwi.QuoteRev = ql.QuoteRev
		WHERE	qwi.ProcessNum = '04' -- solo imballo

		-- inserisco dati mancanti di DSR x incestatura come 1 - OUT/IN
		UPDATE	qwi
		SET		DSR = 1 - CAST(td.TotOUT AS DECIMAL(18,6))/CAST(td.TotIN AS DECIMAL(18,6))
		FROM	#QuoteWorkInt qwi
		INNER JOIN dbo.TabDifett td ON qwi.Class05 = td.KeyAMI AND qwi.ProcessNum = td.ProcessNum 
		WHERE	qwi.ProcessNum = '04' -- solo imballo
		
		-- recupero le MAC fase 01
		SELECT	 
				 @MAC_SC	= MCR
				,@MAC_ST	= WCR
		FROM	#QuoteWorkInt WITH (NOLOCK)
		WHERE	ProcessNum = '01'

		-- recupero le MAC fase 02
		SELECT	 
				@MAC_IN		= DCR
		FROM	#QuoteWorkInt  WITH (NOLOCK)
		WHERE   ProcessNum = '02'

		-- recupero le MAC fase 04
		SELECT	 
				@MAC_IM		= DCR
		FROM	#QuoteWorkInt  WITH (NOLOCK)
		WHERE	ProcessNum = '04'
		
		-- calcolo percentuale vendita rottame
		SELECT	@SSR = SSR
		FROM	dbo.RawMatDet
		WHERE	RawMat = @RawMat
				

        -- NOTA :   la transazione posso probabilmente iniziarla qui visto che è il 
        --          primo Update/insert/delete su tabelle non temporanee

		-- update rese RawMat!
		UPDATE	dbo.QuoteRM
		SET		FCR = @MAC_SC * @MAC_ST * @MAC_IN * @MAC_IM
		WHERE	QuoteType	= @QuoteType
			AND	CodQuote	= @CodQuote
			AND	QuoteRev	= @QuoteRev
			AND	RawMat		= @RawMat

		-- inserisco i costi delle utilities in QuoteOC
			
		-- inserisco altri costi x lavorazione estrusione! GAS ed EE
		INSERT INTO #QuoteOC(QuoteType, CodQuote, QuoteRev, ProcessNum, CodPlant, Class01, Class02, TotQty, TotCost, Quota)
		SELECT	@QuoteType, @CodQuote, @QuoteRev, '01', @CodPlant, CodUtil, @RawMat, @BatchQty, UnitCost * @BatchQty, 1
		FROM	dbo.Utilities
		WHERE	CodPlant = @CodPlant
		

		/*************************************************************
		* MATRICE
		*
		* calcolo prezzo e durata matrice con procedura a 5 step...
		* A) media ponderata prezzo ed ExpLife da DiesDet selezionando x CodItem + CodDiesGroup 
		* B) EOLLife x media ponderata su DiesDet dove Active = 0
		* C) SE prezzo = 0 --> prendo prezzo da DiesGroupDet selezionando x CodDiesGroup
		* D) Se EOL = 0 --> prendo ExpLife della singola matrice, se è 0 --> prendo EOLLife da DiesGroupDet selezionando x CodDiesGroup
		* E) Calcolo Price / Life
		*
		*************************************************************/

		-- (A) da DiesDet
		SELECT	@DiesPrice		= SUM(ISNULL(Price, 0) * ISNULL(ActLife, 1)) / SUM(ISNULL(ActLife, 1)), 
				@DiesExpLife	= SUM(ISNULL(ExpLife, 0) * ISNULL(ActLife, 1)) / SUM(ISNULL(ActLife, 1))
		FROM	dbo.DiesDet
		WHERE	CodItem			= @CodItem 
			AND	CodDiesGroup	= @CodDiesGroup
		GROUP BY CodItem, CodDiesGroup

		-- (B) da DiesDet
		SELECT	@DiesEOLife		= AVG(ISNULL(ActLife, 0))
		FROM	dbo.DiesDet
		WHERE	CodItem			= @CodItem 
			AND	CodDiesGroup	= @CodDiesGroup
			AND	Active			= 0
		GROUP BY CodItem, CodDiesGroup
		
		SET	@DiesPrice		= ISNULL(@DiesPrice,0)
		SET	@DiesExpLife	= ISNULL(@DiesExpLife,0)
		SET	@DiesEOLife		= ISNULL(@DiesEOLife,0)

		-- (C) verifico se prezzo è OK...
		IF (@DiesPrice = 0)
		BEGIN
			-- calcolo da DiesGroupDet
			SELECT	@DiesPrice		= ISNULL(Price, 0)
			FROM	DiesGroupDet
			WHERE	CodDiesGroup	= @CodDiesGroup
		END
		
		-- (D) verifico se vita è OK...
		IF (@DiesEOLife = 0)
		BEGIN
			-- uso exp life articolo...
			SET	@DiesEOLife = @DiesExpLife
		END
		-- controllo che non sia nulla/vuota la durata...
		IF (@DiesEOLife = 0)
		BEGIN
			SELECT	@DiesEOLife = CASE WHEN EOLLife > 0 THEN EOLLife ELSE ExpLife END
			FROM	DiesGroupDet
			WHERE	CodDiesGroup	= @CodDiesGroup
		END

		-- controllo che non sia nulla/vuota la durata...
		IF (@DiesEOLife = 0)
		BEGIN
			SET	@DiesEOLife = 1 -- metto 1 kg che è sbagliato e mi fa esplodere prezzo matrice ma non blocca calcoli
		END

		-- (E) Calcolo price/life!
		SET	@DiesPriceLife = @DiesPrice / @DiesEOLife
		
		-- (D) verifico se vita è OK...
		IF (@DiesPriceLife = 0)
		BEGIN
			SET @DiesPriceLife = 1 
			SET @valid = 0
		END
		
		-- inserisco costi per Matrice: costo e durata da matrice, se non ci sono da gruppo, (anche solo uno dei due, ovviamente più facile trovare durata x matrice...)
		INSERT INTO #QuoteOC(QuoteType, CodQuote, QuoteRev, ProcessNum, CodPlant, Class01, Class02, TotQty, TotCost, Quota, valid)
		SELECT	@QuoteType, @CodQuote, @QuoteRev, '01', @CodPlant, 'MATRICE', @RawMat, @BatchQty, @DiesPriceLife * @BatchQty, 1, @valid
		

		-- inserisco parametri calcolati x matrice
		INSERT INTO #QuoteParam(QuoteType, CodQuote, QuoteRev, ProcessNum, Descr, Parameter)
		SELECT	@QuoteType, @CodQuote, @QuoteRev, '01', 'DiesPrice', @DiesPrice

		INSERT INTO #QuoteParam(QuoteType, CodQuote, QuoteRev, ProcessNum, Descr, Parameter)
		SELECT	@QuoteType, @CodQuote, @QuoteRev, '01', 'DiesExpLife', @DiesExpLife

		INSERT INTO #QuoteParam(QuoteType, CodQuote, QuoteRev, ProcessNum, Descr, Parameter)
		SELECT	@QuoteType, @CodQuote, @QuoteRev, '01', 'DiesEOLife', @DiesEOLife

		/*************************************************************
		* VENDITA ROTTAME
		*
		* calcolo COSTO DI VENDITA PER LE 2 FASI ESTRUSIONE 01 ED IMBALLO 04
		* - calcolo costi variabili fase 01 / 04
		* - calcolo costo di vendita x fase 01 / 04
		*************************************************************/

		SELECT	@OCF01 = SUM(ISNULL(C4UG,0))
		FROM	#QuoteOC  WITH (NOLOCK)
			
		SELECT	@VCF01 = @OCF01 + VC4UG	
		FROM	#QuoteWorkInt
		WHERE	ProcessNum	= '01'
			
		SELECT	@VCF04 = @OCF01 + SUM(VC4UG)
		FROM	#QuoteWorkInt
			
		SELECT	@SellCostF01 = ((@MAC_ST * @MAC_SC * @MAC_IN) - 1) * (q.RawMatCost  + q.RawMatExtraCost - CASE WHEN SSVA > 0 THEN SSVA ELSE q.RawMatCost * SSVR END + @VCF01) -- ((prodotto delle MAC = inverso del prodotto delle rese) - 1) * (costo Al - prezzo rivendita + costi var fase 01)
			  , @RefCostF01  = -- ( (A - B) / 100 - C )
							   (
								-- (A) = (costo pieno di acquisto + costi fase 1) * MAC * 100 (IN CENTESIMI)
							   	((q.RawMatCost + q.RawMatExtraCost + @VCF01) * (@MAC_ST * @MAC_SC * @MAC_IN * 100))
								-- (B) = ((MAC * 100) - 100) * Resa di fonderia * (costo pieno acquisto - costo di trasformazione))
							  -	((@MAC_ST * @MAC_SC * @MAC_IN * 100) - 100) * rmd.ProcYield * (q.RawMatCost + q.RawMatExtraCost + @VCF01 - rmd.ProcCost)
							   ) / 100 -- divido per 100 finale
							    -- (C) = sottraggo costo pieno alluminio
							  - (q.RawMatCost + q.RawMatExtraCost + @VCF01)
		FROM	dbo.RawMatDet rmd 
		INNER JOIN dbo.QuoteRM q ON q.RawMat = rmd.RawMat
		WHERE	q.QuoteType	= @QuoteType
			AND	q.CodQuote	= @CodQuote
			AND	q.QuoteRev	= @QuoteRev
			AND	q.RawMat	= @RawMat
			
		SELECT	@SellCostF04 = ((@MAC_IM) - 1) * (q.RawMatCost  + q.RawMatExtraCost - CASE WHEN SSVA > 0 THEN SSVA ELSE q.RawMatCost * SSVR END + @VCF01 + @VCF04) -- ((prodotto delle MAC = inverso del prodotto delle rese) - 1) * (costo Al - prezzo rivendita + costi var fase 04)
			  , @RefCostF04  = -- ( (A - B) / 100 - C )
							   (
								-- (A) = (costo pieno di acquisto + costi variabili fase 1 e 4) * MAC * 100 (IN CENTESIMI)
							   	((q.RawMatCost + q.RawMatExtraCost + @VCF01 + @VCF04) * (@MAC_IM * 100))
								-- (B) = ((MAC * 100) - 100) * Resa di fonderia * (costo pieno acquisto - costo di trasformazione))
							  -	((@MAC_IM * 100) - 100) * rmd.ProcYield * (q.RawMatCost + q.RawMatExtraCost + @VCF01 + @VCF04 - rmd.ProcCost)
							   ) / 100 -- divido per 100 finale
							    -- (C) = sottraggo costo pieno alluminio
							  - (q.RawMatCost + q.RawMatExtraCost + @VCF01 + @VCF04)

							  -- NOTA: usiamo (q.RawMatCost + q.RawMatExtraCost + @VCF01) e non (q.RawMatCost + q.RawMatExtraCost + @VCF01 + @RefCostF01) perché la differenza è minimale, si tratta di 10/20 PPM...

		FROM	RawMatDet rmd INNER JOIN QuoteRM q ON q.RawMat = rmd.RawMat
		WHERE	q.QuoteType	= @QuoteType
			AND	q.CodQuote	= @CodQuote
			AND	q.QuoteRev	= @QuoteRev
			AND	q.RawMat	= @RawMat
		
		-- inserisco costi per VENDITA
		INSERT INTO #QuoteOC(QuoteType, CodQuote, QuoteRev, ProcessNum, CodPlant, Class01, Class02, TotQty, TotCost, Quota)
		SELECT	@QuoteType, @CodQuote, @QuoteRev, '01', @CodPlant, 'VENDITA', @RawMat, @BatchQty, @SellCostF01 * @BatchQty, @SSR

		-- inserisco costi per ROTTAME
		INSERT INTO #QuoteOC(QuoteType, CodQuote, QuoteRev, ProcessNum, CodPlant, Class01,  Class02, TotQty, TotCost, Quota)
		SELECT	@QuoteType, @CodQuote, @QuoteRev, '01', @CodPlant, 'ROTTAME', @RawMat, @BatchQty, @RefCostF01 * @BatchQty, 1 - @SSR
		
		-- inserisco costi per VENDITA
		INSERT INTO #QuoteOC(QuoteType, CodQuote, QuoteRev, ProcessNum, CodPlant, Class01, Class02, TotQty, TotCost, Quota)
		SELECT	@QuoteType, @CodQuote, @QuoteRev, '04', @CodPlant, 'VENDITA', @RawMat, @BatchQty, @SellCostF04 * @BatchQty, @SSR

		-- inserisco costi per ROTTAME
		INSERT INTO #QuoteOC(QuoteType, CodQuote, QuoteRev, ProcessNum, CodPlant, Class01,  Class02, TotQty, TotCost, Quota)
		SELECT	@QuoteType, @CodQuote, @QuoteRev, '04', @CodPlant, 'ROTTAME', @RawMat, @BatchQty, @RefCostF04 * @BatchQty, 1 - @SSR
	
		EXEC stp_packageCost @CodItem, @CodClient, @CodPackag, @PDesc=@PkgDesc OUTPUT, @RMWeight=@PRMWeight OUTPUT, @Weight=@PWeight OUTPUT, @Tare=@PTare OUTPUT, @PackCost=@PCost OUTPUT, @TareStRat=@PTareStRatio OUTPUT
			
		-- inserisco costi per IMBALLO
		INSERT INTO #QuoteOC(QuoteType, CodQuote, QuoteRev, ProcessNum, CodPlant, Class01,  Class02, TotQty, TotCost, Quota)
		SELECT	@QuoteType, @CodQuote, @QuoteRev, '04', @CodPlant, 'IMBALLO', @RawMat, @BatchQty, @PCost * @BatchQty, 1


		-- inserisco parametri calcolati x imballaggio
		INSERT INTO #QuoteParam(QuoteType, CodQuote, QuoteRev, ProcessNum, Descr, Parameter)
		SELECT	@QuoteType, @CodQuote, @QuoteRev, '04', 'PkgDesc', @PkgDesc

		INSERT INTO #QuoteParam(QuoteType, CodQuote, QuoteRev, ProcessNum, Descr, Parameter)
		SELECT	@QuoteType, @CodQuote, @QuoteRev, '04', 'PRMWeight', @PRMWeight

		INSERT INTO #QuoteParam(QuoteType, CodQuote, QuoteRev, ProcessNum, Descr, Parameter)
		SELECT	@QuoteType, @CodQuote, @QuoteRev, '04', 'PWeight', @PWeight

		INSERT INTO #QuoteParam(QuoteType, CodQuote, QuoteRev, ProcessNum, Descr, Parameter)
		SELECT	@QuoteType, @CodQuote, @QuoteRev, '04', 'PTare', @PTare

		INSERT INTO #QuoteParam(QuoteType, CodQuote, QuoteRev, ProcessNum, Descr, Parameter)
		SELECT	@QuoteType, @CodQuote, @QuoteRev, '04', 'TareStRatio', @PTareStRatio
		
		
		---------------------------------------------	
		-- inserisco costi per TRASPORTI
		---------------------------------------------
		-- recupero zona da cliente...
		SELECT	@TranspZone = TranspZone
		FROM	dbo.ClientDet	
		WHERE	CodClient	= @CodClient

		-- recupero tipo di trasporto
		SELECT	@HasTC = ISNULL(i.HasTC, 0)
		FROM	dbo.QuoteList q INNER JOIN Incoterms i ON q.CodInco = i.CodInco
		WHERE	q.QuoteType	= @QuoteType
			AND	q.CodQuote	= @CodQuote
			AND	q.QuoteRev	= @QuoteRev

		-- recupero costi trasporto
		SELECT	@TranspCost = TranspCost
		FROM	dbo.TranspCostDet
		WHERE	TranspZone	= @TranspZone

		INSERT INTO #QuoteOC(QuoteType, CodQuote, QuoteRev, ProcessNum, CodPlant, Class01,  Class02, TotQty, TotCost, Quota)
		SELECT	@QuoteType, @CodQuote, @QuoteRev, '04', @CodPlant, 'TRASPORTI', @RawMat, @BatchQty, @HasTC * @TranspCost * @BatchQty, 1

		
		---------------------------------------------	
		-- inserisco costi per PROVVIGIONI
		---------------------------------------------
		SELECT	@Provvig = ISNULL(a.QuotaProvvAg, 0)
		FROM	dbo.AgentsDet a
		INNER JOIN ClientDet c ON a.CodAg = c.CodAg
		INNER JOIN QuoteList q ON q.CodClient = c.CodClient
		WHERE	q.QuoteType	= @QuoteType
			AND	q.CodQuote	= @CodQuote
			AND	q.QuoteRev	= @QuoteRev

		-- inserisco costi per PROVVIGIONI
		INSERT INTO #QuoteOC(QuoteType, CodQuote, QuoteRev, ProcessNum, CodPlant, Class01,  Class02, TotQty, TotCost, Quota)
		SELECT	@QuoteType, @CodQuote, @QuoteRev, '04', @CodPlant, 'PROVVIGIONI', @RawMat, @BatchQty, @Provvig * @BatchQty, 1

        /* ==================================================
             CANCELLO E CARICO TABELLE EFFETTIVE
           ==================================================*/

		-- elimino e carico parametri!
		DELETE FROM	dbo.QuoteParam
		WHERE	QuoteType	= @QuoteType
			AND	CodQuote	= @CodQuote
			AND	QuoteRev	= @QuoteRev

		INSERT dbo.QuoteParam
		SELECT * FROM #QuoteParam WITH (NOLOCK)

		-- elimino e carico lavorazioni interne!
		DELETE FROM	dbo.QuoteWorkInt
		WHERE	QuoteType	= @QuoteType
			AND	CodQuote	= @CodQuote
			AND	QuoteRev	= @QuoteRev

		INSERT dbo.QuoteWorkInt  -- ci sono valori calcolati quindi devo selezionare i campi
		SELECT QuoteType, CodQuote, QuoteRev, NumWI, ProcessNum, CodPlant, Class01, Class02, Class03, Class04, Class05
             , NetProd, WSR, MSR, DSR, FC4UG, VC4UG, OH4UG, SC4UG, valid 
        FROM #QuoteWorkInt WITH (NOLOCK)

		-- elimino e carico OtherCosts
		DELETE FROM	dbo.QuoteOC
		WHERE	QuoteType	= @QuoteType
			AND	CodQuote	= @CodQuote
			AND	QuoteRev	= @QuoteRev

		INSERT dbo.QuoteOC  -- ci sono valori calcolati quindi devo selezionare i campi
		SELECT QuoteType, CodQuote, QuoteRev, NumEx, ProcessNum, CodPlant, Class01, Class02, Class03, Class04
             , Class05, TotQty, TotCost, Quota, valid
        FROM #QuoteOC WITH (NOLOCK)


	COMMIT TRAN
	
	--SELECT * FROM #QuoteParam
	--SELECT * FROM #QuoteWorkInt
	--SELECT * FROM #QuoteOC

	-- elimino temp table...
	IF OBJECT_ID('tempdb..#QuoteParam') IS NOT NULL
		DROP TABLE #QuoteParam
    IF OBJECT_ID('tempdb..#QuoteWorkInt') IS NOT NULL
		DROP TABLE #QuoteWorkInt
    IF OBJECT_ID('tempdb..#QuoteOC') IS NOT NULL
		DROP TABLE #QuoteOC

END
GO
PRINT N'Creating [dbo].[stp_QL_update_SAM]...';


GO
-- =============================================
-- Author:		S.E. Locatelli
-- Create date: 2013.12.13
-- Description:	aggiorna tabella QuoteList con i dati selezionati dalla TabProdSc
-- =============================================
CREATE PROCEDURE [dbo].[stp_QL_update_SAM]
(
    @QuoteType	CHAR(1) = 'Q',
    @CodQuote	BIGINT	= 0,
    @QuoteRev	INT		= 0
) 
AS
BEGIN

    SET NOCOUNT ON;
    SET XACT_ABORT ON;
        
    BEGIN TRAN

        -- dichiaro valori da recuperare
        DECLARE	@cont			INT = 0 -- contatore x numeri consecutivi...
        DECLARE	@strTemp		NVARCHAR(50) = '' --stringa temporanea x variabili "locali"

        DECLARE @valid			BIT
        DECLARE @CodDiesGroup	NVARCHAR(50)
        DECLARE @CodPlant		NVARCHAR(50)
        DECLARE @CodPlantFix	NVARCHAR(50) = ''
        DECLARE @HoleNum		INT
        DECLARE @CodItem		NVARCHAR(50) = '' --cod item
        DECLARE @ItemDescr		NVARCHAR(50) = '' -- descrizione item
        DECLARE @KeyAM			NVARCHAR(50) = ''
        DECLARE @KeyAMI			NVARCHAR(50) = ''
        DECLARE @KeyAMIL		NVARCHAR(50) = ''
        DECLARE @NumSMED		INT = 0 -- numero cambi
        DECLARE @KgTeo			DECIMAL(18, 6) = 0 -- kg totali
        DECLARE @RawMat			NVARCHAR(50)
        DECLARE	@ProdTeo		DECIMAL(18,6)
        DECLARE	@ScTec			DECIMAL(18,6)
        DECLARE	@BatchQty		INT
        DECLARE	@MAC_SC			DECIMAL(18,6) -- Messa a cento scarto cesoia
        DECLARE	@MAC_ST			DECIMAL(18,6) -- Messa a cento scarto tecnico
        DECLARE	@MAC_IN			DECIMAL(18,6) -- Messa a cento difettosità all'incestatura
        DECLARE	@MAC_IM			DECIMAL(18,6) -- Messa a cento difettosità all'imballo
        DECLARE	@SSR			DECIMAL(9,6) -- percentuale vendita rottame
        DECLARE	@DiesPrice		DECIMAL(9,3) -- prezzo matrice
        DECLARE	@DiesEOLife		DECIMAL(9,2) -- durata matrice
        DECLARE	@DiesExpLife	DECIMAL(9,2) -- durata matrice
        DECLARE	@DiesPriceLife	DECIMAL(18,6) -- Price/Life matrice
        DECLARE	@OCF01			DECIMAL(18,6) = 0 -- altri costi di fase 01
        DECLARE	@VCF01			DECIMAL(18,6) = 0 -- costi variabili di fase 01
        DECLARE	@VCF04			DECIMAL(18,6) = 0 -- costi variabili di fase 04
        DECLARE	@SellCostF01	DECIMAL(18,6) = 0 -- costo vendita fase 01
        DECLARE	@SellCostF04	DECIMAL(18,6) = 0 -- costo vendita fase 04
        DECLARE	@RefCostF01		DECIMAL(18,6) = 0 -- costo rifusione fase 01 
        DECLARE	@RefCostF04		DECIMAL(18,6) = 0 -- costo rifusione fase 04
        -- IMBALLO
        DECLARE	@CodPackag		NVARCHAR(50) = '0' -- codice dell'imballo
        DECLARE @CodClient		NVARCHAR(50) = '' -- codice cliente
        DECLARE @NumImb			DECIMAL(9,6) = 0 -- num imballatori
        DECLARE @PkgDesc		NVARCHAR(50) = '' -- descrizione imballo
        DECLARE @PRMWeight		DECIMAL(9,4) = 0 -- peso dell'imballo
        DECLARE @PWeight		DECIMAL(9,4) = 0 -- peso del pacco
        DECLARE @PTare			DECIMAL(9,4) = 0 -- media delal tara di imballo dichiarata
        DECLARE @PCost			DECIMAL(9,6) = 0 -- costo unitario dell'imballo (al kg) 
        DECLARE @PTareStRatio	DECIMAL(9,4) = 0 -- coefficiente di recupero tara/prodotto

        -- TRASPORTI
        DECLARE	@TranspZone		NVARCHAR(50) = '', -- codice ZONA
                @TranspCost		DECIMAL(9,6), -- costo di trasporto
                @HasTC			INT

        -- PROVVIGIONI
        DECLARE	@Provvig		DECIMAL(9,6) -- provvigione agente


        -- default: validità è true!
        SET		@valid = 1


        ---------------------------------------
        -- svuotamento iniziale
        ---------------------------------------
        -- elimino parametri!
        DELETE 
        FROM	dbo.QuoteParam
        WHERE	QuoteType	= @QuoteType
            AND	CodQuote	= @CodQuote
            AND	QuoteRev	= @QuoteRev
            
        -- elimino lavorazioni interne!
        DELETE 
        FROM	dbo.QuoteWorkInt
        WHERE	QuoteType	= @QuoteType
            AND	CodQuote	= @CodQuote
            AND	QuoteRev	= @QuoteRev
            
        -- elimino preventivamente OtherCosts già inseriti!
        DELETE 
        FROM	dbo.QuoteOC
        WHERE	QuoteType	= @QuoteType
            AND	CodQuote	= @CodQuote
            AND	QuoteRev	= @QuoteRev

        -- elimino lavorazioni esterne!
        DELETE 
        FROM	dbo.QuoteWorkExt
        WHERE	QuoteType	= @QuoteType
            AND	CodQuote	= @CodQuote
            AND	QuoteRev	= @QuoteRev

        -- se ci sono eccezioni nella tab dell'anagrafico articoli imposto il codPlant desiderato
        SET	@CodPlantFix = ISNULL ( ( SELECT id.CodPlant FROM dbo.ItemDet id INNER JOIN dbo.QuoteList ql ON id.CodItem = ql.CodItem
                                      WHERE  ql.QuoteType   = @QuoteType
                                      AND    ql.CodQuote    = @CodQuote
                                      AND    ql.QuoteRev    = @QuoteRev ), '' )

        -- recupero da dati dell'offerta il valore del cliente
        SELECT	@CodClient		= CodClient
        FROM	dbo.QuoteList
        WHERE	QuoteType		= @QuoteType
            AND	CodQuote		= @CodQuote
            AND	QuoteRev		= @QuoteRev

            
        -- recupero da dati dell'offerta il valore del package scelto
        SELECT	@CodPackag		= CodPackag
        FROM	dbo.QuoteRM
        WHERE	QuoteType		= @QuoteType
            AND	CodQuote		= @CodQuote
            AND	QuoteRev		= @QuoteRev

        -- recupero dati!!
        SELECT	TOP 1 @CodItem	= ql.CodItem
                    , @CodDiesGroup = tps.CodDiesGroup
                    , @CodPlant = CASE WHEN @CodPlantFix <> '' THEN @CodPlantFix ELSE tps.CodPlant END
                    , @HoleNum = tps.HoleNum
                    , @KeyAM	= ql.KeyAM
                    , @KeyAMI	= ql.KeyAM + '-' + ISNULL(@CodPlant,'0000')
                    , @KeyAMIL	= ql.KeyAM + '-' + ISNULL(@CodPlant,'0000') + '-' + CAST(ISNULL(tps.HoleNum,0) AS NVARCHAR(10))
                    , @ProdTeo	= tps.ProdTeo
                    , @ScTec	= tps.ScTec
                    , @KgTeo	= tps.KgTeo
                    , @NumSMED	= tps.NumSMED
                    , @RawMat	= ql.RawMat
                    , @BatchQty	= ql.BatchQty
                    , @ItemDescr= i.ItemDescr
        FROM dbo.QuoteList ql 
        INNER JOIN dbo.TabProdSc tps ON ql.KeyAM = tps.KeyAM 
        INNER JOIN dbo.ItemDet i ON ql.CodItem = i.CodItem
        WHERE	ql.QuoteType	= @QuoteType
            AND	ql.CodQuote		= @CodQuote
            AND	ql.QuoteRev		= @QuoteRev
        ORDER BY tps.KgTeo DESC
        
        
        -- inserisco note sull'articolo
        SELECT	@cont = ISNULL(MAX(NumP),0) + 1
        FROM	dbo.QuoteParam
        WHERE	QuoteType	= @QuoteType
            AND	CodQuote	= @CodQuote
            AND	QuoteRev	= @QuoteRev

        INSERT INTO dbo.QuoteParam(QuoteType, CodQuote, QuoteRev, NumP, ProcessNum, Descr, Parameter)
        VALUES (@QuoteType, @CodQuote, @QuoteRev, @cont, '01', 'ItemDescr', @ItemDescr)

        SELECT	@cont = @cont + 1
        INSERT INTO dbo.QuoteParam(QuoteType, CodQuote, QuoteRev, NumP, ProcessNum, Descr, Parameter)
        SELECT	@QuoteType, @CodQuote, @QuoteRev, @cont, '01', 'CodifProfilo', Class01
        FROM	dbo.ItemDet
        WHERE	CodItem = @CodItem

        SELECT	@cont = @cont + 1
        INSERT INTO dbo.QuoteParam(QuoteType, CodQuote, QuoteRev, NumP, ProcessNum, Descr, Parameter)
        SELECT	@QuoteType, @CodQuote, @QuoteRev, @cont, '01', 'ClasseMerc', Class02
        FROM	dbo.ItemDet
        WHERE	CodItem	= @CodItem
        
        SELECT	@cont = @cont + 1	
        INSERT INTO dbo.QuoteParam(QuoteType, CodQuote, QuoteRev, NumP, ProcessNum, Descr, Parameter)
        SELECT	@QuoteType, @CodQuote, @QuoteRev, @cont, '01', 'ClienteAssoc', Class03
        FROM	dbo.ItemDet
        WHERE	CodItem	= @CodItem
        
        -- INFORMAZIONI su MATRICE
        SELECT	@cont = @cont + 1
        INSERT INTO QuoteParam(QuoteType, CodQuote, QuoteRev, NumP, ProcessNum, Descr, Parameter)
        VALUES (@QuoteType, @CodQuote, @QuoteRev, @cont, '01', 'CodDiesGroup', @CodDiesGroup)

        SELECT	@cont = @cont + 1
        SET @strTemp = dbo.f_getSubstring(@CodDiesGroup, '-', 1) --@strTemp = SUBSTRING(@CodDiesGroup, 0, CHARINDEX('-', @CodDiesGroup)) -- !!!fare con finc Gian
        INSERT INTO QuoteParam(QuoteType, CodQuote, QuoteRev, NumP, ProcessNum, Descr, Parameter)
        VALUES (@QuoteType, @CodQuote, @QuoteRev, @cont, '01', 'TipoDies', @strTemp) 

        SELECT	@cont = @cont + 1
        SET @strTemp = dbo.f_getSubstring(@CodDiesGroup, '-', 2) --@strTemp = SUBSTRING(REPLACE(@CodDiesGroup, @strTemp,''), 2, CHARINDEX('-', @CodDiesGroup))	 -- !!!fare con finc Gian
        INSERT INTO QuoteParam(QuoteType, CodQuote, QuoteRev, NumP, ProcessNum, Descr, Parameter)
        VALUES (@QuoteType, @CodQuote, @QuoteRev, @cont, '01', 'DiamDies', @strTemp)

        SELECT	@cont = @cont + 1
        SET @strTemp = dbo.f_getSubstring(@CodDiesGroup, '-', 3) --@strTemp = SUBSTRING(REPLACE(@CodDiesGroup, @strTemp,''), 5, CHARINDEX('-', @CodDiesGroup)) -- !!!fare con finc Gian	
        INSERT INTO QuoteParam(QuoteType, CodQuote, QuoteRev, NumP, ProcessNum, Descr, Parameter)
        VALUES (@QuoteType, @CodQuote, @QuoteRev, @cont, '01', 'HoleNumDies', @strTemp)

        SELECT	@cont = @cont + 1
        INSERT INTO QuoteParam(QuoteType, CodQuote, QuoteRev, NumP, ProcessNum, Descr, Parameter)
        SELECT	@QuoteType, @CodQuote, @QuoteRev, @cont, '01', 'NumDiesInList', COUNT(CodDies)
        FROM	dbo.DiesDet
        WHERE	CodDiesGroup = @CodDiesGroup AND CodItem = @CodItem

        SELECT	@cont = @cont + 1
        INSERT INTO QuoteParam(QuoteType, CodQuote, QuoteRev, NumP, ProcessNum, Descr, Parameter)
        SELECT	@QuoteType, @CodQuote, @QuoteRev, @cont, '01', 'NumDiesExaust', COUNT(CodDies)
        FROM	dbo.DiesDet
        WHERE	CodDiesGroup = @CodDiesGroup AND Active = 0
        
            
        -- inserisco lavorazione estrusione!
        INSERT INTO dbo.QuoteWorkInt(QuoteType, CodQuote, QuoteRev, NumWI, ProcessNum, CodPlant, Class01, Class02, Class03, NetProd, WSR)
        SELECT	@QuoteType, @CodQuote, @QuoteRev, ISNULL(MAX(NumWI),0) + 1, '01', @CodPlant, @KeyAM, @KeyAMIL, @RawMat, @ProdTeo, @ScTec
        FROM	QuoteWorkInt
        WHERE	QuoteType	= @QuoteType
            AND	CodQuote	= @CodQuote
            AND	QuoteRev	= @QuoteRev

            
        -- inserisco parametri calcolati x lavorazione estruzione
        INSERT INTO dbo.QuoteParam(QuoteType, CodQuote, QuoteRev, NumP, ProcessNum, Descr, Parameter)
        SELECT	@QuoteType, @CodQuote, @QuoteRev, ISNULL(MAX(NumP),0) + 1, '01', 'CodPlant', @CodPlant
        FROM	dbo.QuoteParam
        WHERE	QuoteType	= @QuoteType
            AND	CodQuote	= @CodQuote
            AND	QuoteRev	= @QuoteRev	

        INSERT INTO QuoteParam(QuoteType, CodQuote, QuoteRev, NumP, ProcessNum, Descr, Parameter)
        SELECT	@QuoteType, @CodQuote, @QuoteRev, ISNULL(MAX(NumP),0) + 1, '01', 'KeyAM', @KeyAM
        FROM	QuoteParam
        WHERE	QuoteType	= @QuoteType
            AND	CodQuote	= @CodQuote
            AND	QuoteRev	= @QuoteRev	

        INSERT INTO QuoteParam(QuoteType, CodQuote, QuoteRev, NumP, ProcessNum, Descr, Parameter)
        SELECT	@QuoteType, @CodQuote, @QuoteRev, ISNULL(MAX(NumP),0) + 1, '01', 'KeyAMIL', @KeyAMIL
        FROM	QuoteParam
        WHERE	QuoteType	= @QuoteType
            AND	CodQuote	= @CodQuote
            AND	QuoteRev	= @QuoteRev

        INSERT INTO QuoteParam(QuoteType, CodQuote, QuoteRev, NumP, ProcessNum, Descr, Parameter)
        SELECT	@QuoteType, @CodQuote, @QuoteRev, ISNULL(MAX(NumP),0) + 1, '01', 'NumCambi', @NumSMED
        FROM	QuoteParam
        WHERE	QuoteType	= @QuoteType
            AND	CodQuote	= @CodQuote
            AND	QuoteRev	= @QuoteRev	

        INSERT INTO QuoteParam(QuoteType, CodQuote, QuoteRev, NumP, ProcessNum, Descr, Parameter)
        SELECT	@QuoteType, @CodQuote, @QuoteRev, ISNULL(MAX(NumP),0) + 1, '01', 'KgTeo', @KgTeo
        FROM	QuoteParam
        WHERE	QuoteType	= @QuoteType
            AND	CodQuote	= @CodQuote
            AND	QuoteRev	= @QuoteRev	

        INSERT INTO QuoteParam(QuoteType, CodQuote, QuoteRev, NumP, ProcessNum, Descr, Parameter)
        SELECT	@QuoteType, @CodQuote, @QuoteRev, ISNULL(MAX(NumP),0) + 1, '01', 'HoleNum', @HoleNum
        FROM	QuoteParam
        WHERE	QuoteType	= @QuoteType
            AND	CodQuote	= @CodQuote
            AND	QuoteRev	= @QuoteRev	

        SELECT	@cont = ISNULL(MAX(NumP),0) + 1
        FROM	QuoteParam
        WHERE	QuoteType	= @QuoteType
            AND	CodQuote	= @CodQuote
            AND	QuoteRev	= @QuoteRev

        INSERT INTO QuoteParam(QuoteType, CodQuote, QuoteRev, NumP, ProcessNum, Descr, Parameter)
        SELECT	@QuoteType, @CodQuote, @QuoteRev, @cont, '01', 'KgProdotti', SUM(KgTeo)
        FROM	QuoteList ql 
        INNER JOIN TabProdSc tps ON ql.KeyAM = tps.KeyAM
        WHERE	ql.QuoteType	= @QuoteType
            AND	ql.CodQuote		= @CodQuote
            AND	ql.QuoteRev		= @QuoteRev
            
        --SELECT	@cont = @cont + 1
        --INSERT INTO QuoteParam(QuoteType, CodQuote, QuoteRev, NumP, ProcessNum, Descr, Parameter)
        --SELECT	@QuoteType, @CodQuote, @QuoteRev, @cont, '01', 'NumLotti', COUNT(*)
        --FROM	QuoteList ql INNER JOIN TabProdSc tps ON ql.KeyAM = tps.KeyAM
        --WHERE	ql.QuoteType	= @QuoteType
        --	AND	ql.CodQuote		= @CodQuote
        --	AND	ql.QuoteRev		= @QuoteRev

        -- inserisco dati mancanti di MSR/CSR (scarto cesoia x estrusione) - DSR è NULLO x estrusione!
        UPDATE	qwi
        SET		MSR = rmd.CSR
        FROM	dbo.QuoteWorkInt qwi
        INNER JOIN RawMatDet rmd ON qwi.Class03 = rmd.RawMat
        WHERE	    qwi.QuoteType	= @QuoteType
                AND	qwi.CodQuote	= @CodQuote
                AND	qwi.QuoteRev	= @QuoteRev		

        -- calcolo i costi legati alla fase estrusione!
        UPDATE	qwi
        SET		FC4UG = (cp.FC * cp.QuotaPlantStd / cp.QuotaManStd) / qwi.NetProd
              , VC4UG = (cp.VC * cp.QuotaPlantStd / cp.QuotaManStd) / qwi.NetProd
              , OH4UG = (cp.OH * cp.QuotaPlantStd / cp.QuotaManStd) / qwi.NetProd
              , SC4UG = cp.SC / ql.BatchQty
        FROM	dbo.QuoteWorkInt qwi
            INNER JOIN Cost2Plant cp ON qwi.CodPlant = cp.CodPlant AND qwi.ProcessNum = cp.ProcessNum
            INNER JOIN QuoteList ql ON qwi.QuoteType = ql.QuoteType AND qwi.CodQuote = ql.CodQuote AND qwi.QuoteRev = ql.QuoteRev
        WHERE	    qwi.QuoteType	= @QuoteType
                AND	qwi.CodQuote	= @CodQuote
                AND	qwi.QuoteRev	= @QuoteRev		

        -- inserisco lavorazione incestatura!
        INSERT INTO QuoteWorkInt(QuoteType, CodQuote, QuoteRev, NumWI, ProcessNum, CodPlant, Class01, Class02, Class03)
        SELECT	@QuoteType, @CodQuote, @QuoteRev, ISNULL(MAX(NumWI),0) + 1, '02', @CodPlant, @KeyAM, @KeyAMI, @RawMat
        FROM	dbo.QuoteWorkInt
        WHERE	QuoteType	= @QuoteType
            AND	CodQuote	= @CodQuote
            AND	QuoteRev	= @QuoteRev
        
        
        -- inserisco dati mancanti di DSR x incestatura come 1 - OUT/IN
        UPDATE	qwi
        SET		DSR = 1 - CAST(td.TotOUT AS DECIMAL(18,6))/CAST(td.TotIN AS DECIMAL(18,6))
        FROM	dbo.QuoteWorkInt qwi
        INNER JOIN dbo.TabDifett td ON qwi.Class02 = td.KeyAMI AND qwi.ProcessNum = td.ProcessNum
        WHERE	qwi.ProcessNum = '02' -- solo incestatura
        
        -- inserisco lavorazione FORNO!
        INSERT INTO dbo.QuoteWorkInt(QuoteType, CodQuote, QuoteRev, NumWI, ProcessNum, CodPlant, Class01, Class02, Class03)
        SELECT	@QuoteType, @CodQuote, @QuoteRev, ISNULL(MAX(NumWI),0) + 1, '03', @CodPlant, @KeyAM, @KeyAMI, @RawMat
        FROM	dbo.QuoteWorkInt
        WHERE	QuoteType	= @QuoteType
            AND	CodQuote	= @CodQuote
            AND	QuoteRev	= @QuoteRev
        
        -- inserisco lavorazione imballo!
        INSERT INTO dbo.QuoteWorkInt(QuoteType, CodQuote, QuoteRev, NumWI, ProcessNum, CodPlant, Class01, Class02, Class03, Class04, Class05)
        SELECT	@QuoteType, @CodQuote, @QuoteRev, ISNULL(MAX(NumWI),0) + 1, '04', @CodPlant, @KeyAM, @KeyAMIL, @RawMat, @CodItem, @KeyAMI
        FROM	dbo.QuoteWorkInt
        WHERE	QuoteType	= @QuoteType
            AND	CodQuote	= @CodQuote
            AND	QuoteRev	= @QuoteRev

        -- calcolo produttività netta nella fase imballo
        UPDATE	qwi
        SET		NetProd = ti.TotOut/ ti.Durata
        FROM	dbo.QuoteWorkInt qwi
            INNER JOIN TabImbArt ti ON qwi.Class04 = ti.KeyA

        -- salvo numero imballatori
        SELECT	@NumImb = ISNULL(NumImb,0)
        FROM	TabImbArt
        WHERE	KeyA = @CodItem

        -- parametro num imballatori
        INSERT INTO QuoteParam(QuoteType, CodQuote, QuoteRev, NumP, ProcessNum, Descr, Parameter)
        SELECT	@QuoteType, @CodQuote, @QuoteRev, ISNULL(MAX(NumP),0) + 1, '04', 'NumImballatori', @NumImb
        FROM	QuoteParam
        WHERE	QuoteType	= @QuoteType
            AND	CodQuote	= @CodQuote
            AND	QuoteRev	= @QuoteRev	
        
        -- calcolo i costi legati alla fase di imballo!
        UPDATE	qwi
        SET		FC4UG = (cp.FC * cp.QuotaPlantStd / cp.QuotaManStd) / qwi.NetProd
              , VC4UG = (cp.VC * cp.QuotaPlantStd / cp.QuotaManStd) / qwi.NetProd
              , OH4UG = (cp.OH * cp.QuotaPlantStd / cp.QuotaManStd) / qwi.NetProd
              , SC4UG = cp.SC / ql.BatchQty
        FROM	dbo.QuoteWorkInt qwi
            INNER JOIN Cost2Plant cp ON qwi.CodPlant = cp.CodPlant AND qwi.ProcessNum = cp.ProcessNum
            INNER JOIN QuoteList ql ON qwi.QuoteType = ql.QuoteType AND qwi.CodQuote = ql.CodQuote AND qwi.QuoteRev = ql.QuoteRev
        WHERE	qwi.ProcessNum = '04' -- solo imballo

        
        -- inserisco dati mancanti di DSR x incestatura come 1 - OUT/IN
        UPDATE	qwi
        SET		DSR = 1 - CAST(td.TotOUT AS DECIMAL(18,6))/CAST(td.TotIN AS DECIMAL(18,6))
        FROM	dbo.QuoteWorkInt qwi
            INNER JOIN TabDifett td ON qwi.Class05 = td.KeyAMI AND qwi.ProcessNum = td.ProcessNum 
        WHERE	qwi.ProcessNum = '04' -- solo imballo
        
        
        -- recupero le MAC fase 01
        SELECT	 
                 @MAC_SC	= MCR
                ,@MAC_ST	= WCR
        FROM	dbo.QuoteWorkInt
        WHERE	QuoteType	= @QuoteType
            AND	CodQuote	= @CodQuote
            AND	QuoteRev	= @QuoteRev
            AND	ProcessNum = '01'

        -- recupero le MAC fase 02
        SELECT	 
                @MAC_IN		= DCR
        FROM	dbo.QuoteWorkInt
        WHERE	QuoteType	= @QuoteType
            AND	CodQuote	= @CodQuote
            AND	QuoteRev	= @QuoteRev
            AND	ProcessNum = '02'

        -- recupero le MAC fase 04
        SELECT	 
                @MAC_IM		= DCR
        FROM	dbo.QuoteWorkInt
        WHERE	QuoteType	= @QuoteType
            AND	CodQuote	= @CodQuote
            AND	QuoteRev	= @QuoteRev
            AND	ProcessNum = '04'
        
        -- calcolo percentuale vendita rottame
        SELECT	@SSR = SSR
        FROM	dbo.RawMatDet
        WHERE	RawMat = @RawMat
                
        -- update rese RawMat!
        UPDATE	dbo.QuoteRM
        SET		FCR = @MAC_SC * @MAC_ST * @MAC_IN * @MAC_IM
        WHERE	QuoteType	= @QuoteType
            AND	CodQuote	= @CodQuote
            AND	QuoteRev	= @QuoteRev
            AND	RawMat		= @RawMat




        -- inserisco i costi delle utilities in QuoteOC
            
        -- inserisco altri costi x lavorazione estrusione! GAS ed EE
        INSERT INTO dbo.QuoteOC(QuoteType, CodQuote, QuoteRev, NumEx, ProcessNum, CodPlant, Class01, Class02, TotQty, TotCost, Quota)
        SELECT	@QuoteType, @CodQuote, @QuoteRev, ROW_NUMBER() OVER(ORDER BY CodUtil ASC) AS Row, '01', @CodPlant, CodUtil, @RawMat, @BatchQty, UnitCost * @BatchQty, 1
        FROM	dbo.Utilities
        WHERE	CodPlant = @CodPlant
        

        /*************************************************************
        * MATRICE
        *
        * calcolo prezzo e durata matrice con procedura a 5 step...
        * A) media ponderata prezzo ed ExpLife da DiesDet selezionando x CodItem + CodDiesGroup 
        * B) EOLLife x media ponderata su DiesDet dove Active = 0
        * C) SE prezzo = 0 --> prendo prezzo da DiesGroupDet selezionando x CodDiesGroup
        * D) Se EOL = 0 --> prendo ExpLife della singola matrice, se è 0 --> prendo EOLLife da DiesGroupDet selezionando x CodDiesGroup
        * E) Calcolo Price / Life
        *
        *************************************************************/

        -- (A) da DiesDet
        SELECT	@DiesPrice		= SUM(ISNULL(Price, 0) * ISNULL(ActLife, 1)) / SUM(ISNULL(ActLife, 1)), 
                @DiesExpLife	= SUM(ISNULL(ExpLife, 0) * ISNULL(ActLife, 1)) / SUM(ISNULL(ActLife, 1))
        FROM	dbo.DiesDet
        WHERE	CodItem			= @CodItem 
            AND	CodDiesGroup	= @CodDiesGroup
        GROUP BY CodItem, CodDiesGroup

        -- (B) da DiesDet
        SELECT	@DiesEOLife		= AVG(ISNULL(ActLife, 0))
        FROM	dbo.DiesDet
        WHERE	CodItem			= @CodItem 
            AND	CodDiesGroup	= @CodDiesGroup
            AND	Active			= 0
        GROUP BY CodItem, CodDiesGroup
        
        SET	@DiesPrice		= ISNULL(@DiesPrice,0)
        SET	@DiesExpLife	= ISNULL(@DiesExpLife,0)
        SET	@DiesEOLife		= ISNULL(@DiesEOLife,0)

        -- (C) verifico se prezzo è OK...
        IF (@DiesPrice = 0)
        BEGIN
            -- calcolo da DiesGroupDet
            SELECT	@DiesPrice		= ISNULL(Price, 0)
            FROM	DiesGroupDet
            WHERE	CodDiesGroup	= @CodDiesGroup
        END
        
        -- (D) verifico se vita è OK...
        IF (@DiesEOLife = 0)
        BEGIN
            -- uso exp life articolo...
            SET	@DiesEOLife = @DiesExpLife
        END
        -- controllo che non sia nulla/vuota la durata...
        IF (@DiesEOLife = 0)
        BEGIN
            SELECT	@DiesEOLife = CASE WHEN EOLLife > 0 THEN EOLLife ELSE ExpLife END
            FROM	DiesGroupDet
            WHERE	CodDiesGroup	= @CodDiesGroup
        END

        -- controllo che non sia nulla/vuota la durata...
        IF (@DiesEOLife = 0)
        BEGIN
            SELECT	@DiesEOLife = 1 -- metto 1 kg che è sbagliato e mi fa esplodere prezzo matrice ma non blocca calcoli
        END

        -- (E) Calcolo price/life!
        SET	@DiesPriceLife = @DiesPrice / @DiesEOLife
        
        -- (D) verifico se vita è OK...
        IF (@DiesPriceLife = 0)
        BEGIN
            SET @DiesPriceLife = 1 
            SET @valid = 0
        END
        
        -- inserisco costi per Matrice: costo e durata da matrice, se non ci sono da gruppo, (anche solo uno dei due, ovviamente più facile trovare durata x matrice...)
        INSERT INTO QuoteOC(QuoteType, CodQuote, QuoteRev, NumEx, ProcessNum, CodPlant, Class01, Class02, TotQty, TotCost, Quota, valid)
        SELECT	@QuoteType, @CodQuote, @QuoteRev, ISNULL(MAX(NumEx),0) + 1, '01', @CodPlant, 'MATRICE', @RawMat, @BatchQty, @DiesPriceLife * @BatchQty, 1, @valid
        FROM	QuoteOC
        WHERE	QuoteType	= @QuoteType
            AND	CodQuote	= @CodQuote
            AND	QuoteRev	= @QuoteRev

        
        -- inserisco parametri calcolati x matrice
        INSERT INTO QuoteParam(QuoteType, CodQuote, QuoteRev, NumP, ProcessNum, Descr, Parameter)
        SELECT	@QuoteType, @CodQuote, @QuoteRev, ISNULL(MAX(NumP),0) + 1, '01', 'DiesPrice', @DiesPrice
        FROM	QuoteParam
        WHERE	QuoteType	= @QuoteType
            AND	CodQuote	= @CodQuote
            AND	QuoteRev	= @QuoteRev	

        INSERT INTO QuoteParam(QuoteType, CodQuote, QuoteRev, NumP, ProcessNum, Descr, Parameter)
        SELECT	@QuoteType, @CodQuote, @QuoteRev, ISNULL(MAX(NumP),0) + 1, '01', 'DiesExpLife', @DiesExpLife
        FROM	QuoteParam
        WHERE	QuoteType	= @QuoteType
            AND	CodQuote	= @CodQuote
            AND	QuoteRev	= @QuoteRev	

        INSERT INTO QuoteParam(QuoteType, CodQuote, QuoteRev, NumP, ProcessNum, Descr, Parameter)
        SELECT	@QuoteType, @CodQuote, @QuoteRev, ISNULL(MAX(NumP),0) + 1, '01', 'DiesEOLife', @DiesEOLife
        FROM	QuoteParam
        WHERE	QuoteType	= @QuoteType
            AND	CodQuote	= @CodQuote
            AND	QuoteRev	= @QuoteRev	

        /*************************************************************
        * VENDITA ROTTAME
        *
        * calcolo COSTO DI VENDITA PER LE 2 FASI ESTRUSIONE 01 ED IMBALLO 04
        * - calcolo costi variabili fase 01 / 04
        * - calcolo costo di vendita x fase 01 / 04
        *************************************************************/

        SELECT	@OCF01 = SUM(ISNULL(C4UG,0))
        FROM	QuoteOC
        WHERE	QuoteType	= @QuoteType
            AND	CodQuote	= @CodQuote
            AND	QuoteRev	= @QuoteRev
            
        SELECT	@VCF01 = @OCF01 + VC4UG	
        FROM	QuoteWorkInt
        WHERE	QuoteType	= @QuoteType
            AND	CodQuote	= @CodQuote
            AND	QuoteRev	= @QuoteRev
            AND	ProcessNum	= '01'
            
        SELECT	@VCF04 = @OCF01 + SUM(VC4UG)
        FROM	dbo.QuoteWorkInt
        WHERE	QuoteType	= @QuoteType
            AND	CodQuote	= @CodQuote
            AND	QuoteRev	= @QuoteRev
            
        SELECT	@SellCostF01 = ((@MAC_ST * @MAC_SC * @MAC_IN) - 1) * (q.RawMatCost - CASE WHEN SSVA > 0 THEN SSVA ELSE q.RawMatCost * SSVR END + @VCF01) -- ((prodotto delle MAC = inverso del prodotto delle rese) - 1) * (costo Al - prezzo rivendita + costi var fase 01)
              , @RefCostF01  = -- ( (A - B) / 100 - C )
                               (
                                -- (A) = (costo pieno di acquisto + costi fase 1) * MAC * 100 (IN CENTESIMI)
                                ((q.RawMatCost + q.RawMatExtraCost + @VCF01) * (@MAC_ST * @MAC_SC * @MAC_IN * 100))
                                -- (B) = ((MAC * 100) - 100) * Resa di fonderia * (costo pieno acquisto - costo di trasformazione))
                              -	((@MAC_ST * @MAC_SC * @MAC_IN * 100) - 100) * rmd.ProcYield * (q.RawMatCost + q.RawMatExtraCost + @VCF01 - rmd.ProcCost)
                               ) / 100 -- divido per 100 finale
                                -- (C) = sottraggo costo pieno alluminio
                              - (q.RawMatCost + q.RawMatExtraCost + @VCF01)
        FROM	dbo.RawMatDet rmd 
        INNER JOIN dbo.QuoteRM q ON q.RawMat = rmd.RawMat
        WHERE	q.QuoteType	= @QuoteType
            AND	q.CodQuote	= @CodQuote
            AND	q.QuoteRev	= @QuoteRev
            AND	q.RawMat	= @RawMat
            
        SELECT	@SellCostF04 = ((@MAC_IM) - 1) * (q.RawMatCost - CASE WHEN SSVA > 0 THEN SSVA ELSE q.RawMatCost * SSVR END + @VCF01 + @VCF04) -- ((prodotto delle MAC = inverso del prodotto delle rese) - 1) * (costo Al - prezzo rivendita + costi var fase 04)
              , @RefCostF04  = -- ( (A - B) / 100 - C )
                               (
                                -- (A) = (costo pieno di acquisto + costi fase 1) * MAC * 100 (IN CENTESIMI)
                                ((q.RawMatCost + q.RawMatExtraCost + @VCF01 + @VCF04) * (@MAC_IM * 100))
                                -- (B) = ((MAC * 100) - 100) * Resa di fonderia * (costo pieno acquisto - costo di trasformazione))
                              -	((@MAC_IM * 100) - 100) * rmd.ProcYield * (q.RawMatCost + q.RawMatExtraCost + @VCF01 + @VCF04 - rmd.ProcCost)
                               ) / 100 -- divido per 100 finale
                                -- (C) = sottraggo costo pieno alluminio
                              - (q.RawMatCost + q.RawMatExtraCost + @VCF01 + @VCF04)

                              -- NOTA: usiamo (q.RawMatCost + q.RawMatExtraCost + @VCF01) e non (q.RawMatCost + q.RawMatExtraCost + @VCF01 + @RefCostF01) perché la differenza è minimale, si tratta di 10/20 PPM...

        FROM	RawMatDet rmd INNER JOIN QuoteRM q ON q.RawMat = rmd.RawMat
        WHERE	q.QuoteType	= @QuoteType
            AND	q.CodQuote	= @CodQuote
            AND	q.QuoteRev	= @QuoteRev
            AND	q.RawMat	= @RawMat
        
        -- inserisco costi per VENDITA
        INSERT INTO QuoteOC(QuoteType, CodQuote, QuoteRev, NumEx, ProcessNum, CodPlant, Class01, Class02, TotQty, TotCost, Quota)
        SELECT	@QuoteType, @CodQuote, @QuoteRev, ISNULL(MAX(NumEx),0) + 1, '01', @CodPlant, 'VENDITA', @RawMat, @BatchQty, @SellCostF01 * @BatchQty, @SSR
        FROM	QuoteOC
        WHERE	QuoteType	= @QuoteType
            AND	CodQuote	= @CodQuote
            AND	QuoteRev	= @QuoteRev

        -- inserisco costi per ROTTAME
        INSERT INTO QuoteOC(QuoteType, CodQuote, QuoteRev, NumEx, ProcessNum, CodPlant, Class01,  Class02, TotQty, TotCost, Quota)
        SELECT	@QuoteType, @CodQuote, @QuoteRev, ISNULL(MAX(NumEx),0) + 1, '01', @CodPlant, 'ROTTAME', @RawMat, @BatchQty, @RefCostF01 * @BatchQty, 1 - @SSR
        FROM	QuoteOC
        WHERE	QuoteType	= @QuoteType
            AND	CodQuote	= @CodQuote
            AND	QuoteRev	= @QuoteRev
        
        -- inserisco costi per VENDITA
        INSERT INTO QuoteOC(QuoteType, CodQuote, QuoteRev, NumEx, ProcessNum, CodPlant, Class01, Class02, TotQty, TotCost, Quota)
        SELECT	@QuoteType, @CodQuote, @QuoteRev, ISNULL(MAX(NumEx),0) + 1, '04', @CodPlant, 'VENDITA', @RawMat, @BatchQty, @SellCostF04 * @BatchQty, @SSR
        FROM	QuoteOC
        WHERE	QuoteType	= @QuoteType
            AND	CodQuote	= @CodQuote
            AND	QuoteRev	= @QuoteRev

        -- inserisco costi per ROTTAME
        INSERT INTO QuoteOC(QuoteType, CodQuote, QuoteRev, NumEx, ProcessNum, CodPlant, Class01,  Class02, TotQty, TotCost, Quota)
        SELECT	@QuoteType, @CodQuote, @QuoteRev, ISNULL(MAX(NumEx),0) + 1, '04', @CodPlant, 'ROTTAME', @RawMat, @BatchQty, @RefCostF04 * @BatchQty, 1 - @SSR
        FROM	dbo.QuoteOC
        WHERE	QuoteType	= @QuoteType
            AND	CodQuote	= @CodQuote
            AND	QuoteRev	= @QuoteRev

    
        EXEC stp_packageCost @CodItem, @CodClient, @CodPackag, @PDesc=@PkgDesc OUTPUT, @RMWeight=@PRMWeight OUTPUT, @Weight=@PWeight OUTPUT, @Tare=@PTare OUTPUT, @PackCost=@PCost OUTPUT, @TareStRat=@PTareStRatio OUTPUT
            
        -- inserisco costi per IMBALLO
        INSERT INTO QuoteOC(QuoteType, CodQuote, QuoteRev, NumEx, ProcessNum, CodPlant, Class01,  Class02, TotQty, TotCost, Quota)
        SELECT	@QuoteType, @CodQuote, @QuoteRev, ISNULL(MAX(NumEx),0) + 1, '04', @CodPlant, 'IMBALLO', @RawMat, @BatchQty, @PCost * @BatchQty, 1
        FROM	dbo.QuoteOC
        WHERE	QuoteType	= @QuoteType
            AND	CodQuote	= @CodQuote
            AND	QuoteRev	= @QuoteRev

        -- inserisco parametri calcolati x imballaggio
        INSERT INTO QuoteParam(QuoteType, CodQuote, QuoteRev, NumP, ProcessNum, Descr, Parameter)
        SELECT	@QuoteType, @CodQuote, @QuoteRev, ISNULL(MAX(NumP),0) + 1, '04', 'PkgDesc', @PkgDesc
        FROM	QuoteParam
        WHERE	QuoteType	= @QuoteType
            AND	CodQuote	= @CodQuote
            AND	QuoteRev	= @QuoteRev	

        INSERT INTO QuoteParam(QuoteType, CodQuote, QuoteRev, NumP, ProcessNum, Descr, Parameter)
        SELECT	@QuoteType, @CodQuote, @QuoteRev, ISNULL(MAX(NumP),0) + 1, '04', 'RMWeight', @PRMWeight
        FROM	QuoteParam
        WHERE	QuoteType	= @QuoteType
            AND	CodQuote	= @CodQuote
            AND	QuoteRev	= @QuoteRev	

        INSERT INTO QuoteParam(QuoteType, CodQuote, QuoteRev, NumP, ProcessNum, Descr, Parameter)
        SELECT	@QuoteType, @CodQuote, @QuoteRev, ISNULL(MAX(NumP),0) + 1, '04', 'PWeight', @PWeight
        FROM	QuoteParam
        WHERE	QuoteType	= @QuoteType
            AND	CodQuote	= @CodQuote
            AND	QuoteRev	= @QuoteRev	

        INSERT INTO QuoteParam(QuoteType, CodQuote, QuoteRev, NumP, ProcessNum, Descr, Parameter)
        SELECT	@QuoteType, @CodQuote, @QuoteRev, ISNULL(MAX(NumP),0) + 1, '04', 'PTare', @PTare
        FROM	QuoteParam
        WHERE	QuoteType	= @QuoteType
            AND	CodQuote	= @CodQuote
            AND	QuoteRev	= @QuoteRev	

        INSERT INTO QuoteParam(QuoteType, CodQuote, QuoteRev, NumP, ProcessNum, Descr, Parameter)
        SELECT	@QuoteType, @CodQuote, @QuoteRev, ISNULL(MAX(NumP),0) + 1, '04', 'TareStRatio', @PTareStRatio
        FROM	QuoteParam
        WHERE	QuoteType	= @QuoteType
            AND	CodQuote	= @CodQuote
            AND	QuoteRev	= @QuoteRev	
        
        
        ---------------------------------------------	
        -- inserisco costi per TRASPORTI
        ---------------------------------------------
        -- recupero zona da cliente...
        SELECT	@TranspZone = TranspZone
        FROM	dbo.ClientDet	
        WHERE	CodClient	= @CodClient

        -- recupero tipo di trasporto
        SELECT	@HasTC = ISNULL(i.HasTC, 0)
        FROM	QuoteList q INNER JOIN Incoterms i ON q.CodInco = i.CodInco
        WHERE	q.QuoteType	= @QuoteType
            AND	q.CodQuote	= @CodQuote
            AND	q.QuoteRev	= @QuoteRev

        -- recupero costi trasporto
        SELECT	@TranspCost = TranspCost
        FROM	dbo.TranspCostDet
        WHERE	TranspZone	= @TranspZone

        INSERT INTO QuoteOC(QuoteType, CodQuote, QuoteRev, NumEx, ProcessNum, CodPlant, Class01,  Class02, TotQty, TotCost, Quota)
        SELECT	@QuoteType, @CodQuote, @QuoteRev, ISNULL(MAX(NumEx),0) + 1, '04', @CodPlant, 'TRASPORTI', @RawMat, @BatchQty, @HasTC * @TranspCost * @BatchQty, 1
        FROM	dbo.QuoteOC
        WHERE	QuoteType	= @QuoteType
            AND	CodQuote	= @CodQuote
            AND	QuoteRev	= @QuoteRev

        
        ---------------------------------------------	
        -- inserisco costi per PROVVIGIONI
        ---------------------------------------------
        SELECT	@Provvig = ISNULL(a.QuotaProvvAg, 0)
        FROM	dbo.AgentsDet a
            INNER JOIN ClientDet c ON a.CodAg = c.CodAg
            INNER JOIN QuoteList q ON q.CodClient = c.CodClient
        WHERE	q.QuoteType	= @QuoteType
            AND	q.CodQuote	= @CodQuote
            AND	q.QuoteRev	= @QuoteRev

        -- inserisco costi per PROVVIGIONI
        INSERT INTO QuoteOC(QuoteType, CodQuote, QuoteRev, NumEx, ProcessNum, CodPlant, Class01,  Class02, TotQty, TotCost, Quota)
        SELECT	@QuoteType, @CodQuote, @QuoteRev, ISNULL(MAX(NumEx),0) + 1, '04', @CodPlant, 'PROVVIGIONI', @RawMat, @BatchQty, @Provvig * @BatchQty, 1
        FROM	dbo.QuoteOC
        WHERE	QuoteType	= @QuoteType
            AND	CodQuote	= @CodQuote
            AND	QuoteRev	= @QuoteRev



    COMMIT TRAN

END
GO
PRINT N'Creating [dbo].[stp_QL_getByKey]...';


GO
-- =============================================
-- Author:		Steamware
-- Create date: 2014.02.23
-- Description:	recupera riga QL
-- =============================================
CREATE PROCEDURE dbo.stp_QL_getByKey 
(
	@QuoteType CHAR(1) = 'Q'
	,@CodQuote BIGINT = 0
	,@QuoteRev INT = 0
)
AS

SELECT *
FROM QuoteList
WHERE QuoteType = @QuoteType
	AND CodQuote = @CodQuote
	AND QuoteRev = @QuoteRev

RETURN
GO
PRINT N'Creating [dbo].[stp_QRM_getByKey]...';


GO
-- =============================================
-- Author:		Steamware
-- Create date: 2014.02.23
-- Description:	recupera riga QRM
-- =============================================
create PROCEDURE dbo.stp_QRM_getByKey 
(
	@QuoteType CHAR(1) = 'Q'
	,@CodQuote BIGINT = 0
	,@QuoteRev INT = 0
	,@NumRM INT = 0
)
AS

SELECT *
FROM QuoteRM
WHERE QuoteType = @QuoteType
	AND CodQuote = @CodQuote
	AND QuoteRev = @QuoteRev
	AND NumRM = @NumRM

RETURN
GO
PRINT N'Creating [dbo].[stp_VSRM_SearchLike]...';


GO
-- =============================================
-- Author:		S.E. Locatelli
-- Create date: 2014.02.18
-- Description:	Ricerca materiale Al
-- =============================================
create PROCEDURE [dbo].stp_VSRM_SearchLike
(
	@value NVARCHAR(50)
)

AS
SET NOCOUNT ON;

SELECT value
	,label
FROM v_selRawMat
WHERE (value LIKE '%' + @value + '%')
	OR (label LIKE '%' + @value + '%')
GO
PRINT N'Creating [dbo].[stp_QuoteFull_delete]...';


GO

-- =============================================
-- Author:		Steamware
-- Create date: 2014.02.23
-- Description:	upelimina tutti i record di un offerta
-- =============================================
CREATE PROCEDURE [dbo].[stp_QuoteFull_delete]
(
	@Original_QuoteType CHAR(1) = 'Q'
	,@Original_CodQuote BIGINT = 0
	,@Original_QuoteRev INT = 0
)
AS

SET XACT_ABORT ON;
BEGIN tran
	-- elimino da QuoteFull
	DELETE
	FROM	QuoteFull_Q
	WHERE	QuoteType = @Original_QuoteType
		AND	CodQuote = @Original_CodQuote
		AND	QuoteRev = @Original_QuoteRev

	-- elimino da tab child
	DELETE
	FROM	QuoteWorkExt
	WHERE	QuoteType = @Original_QuoteType
		AND	CodQuote = @Original_CodQuote
		AND	QuoteRev = @Original_QuoteRev
		
	DELETE
	FROM	QuoteWorkInt
	WHERE	QuoteType = @Original_QuoteType
		AND	CodQuote = @Original_CodQuote
		AND	QuoteRev = @Original_QuoteRev
		
	DELETE
	FROM	QuoteOC
	WHERE	QuoteType = @Original_QuoteType
		AND	CodQuote = @Original_CodQuote
		AND	QuoteRev = @Original_QuoteRev
		
	DELETE
	FROM	QuoteParam
	WHERE	QuoteType = @Original_QuoteType
		AND	CodQuote = @Original_CodQuote
		AND	QuoteRev = @Original_QuoteRev

	-- elimino le 2 master: RM e list...
	DELETE
	FROM	QuoteRM
	WHERE	QuoteType = @Original_QuoteType
		AND	CodQuote = @Original_CodQuote
		AND	QuoteRev = @Original_QuoteRev
		
	DELETE
	FROM	QuoteList
	WHERE	QuoteType = @Original_QuoteType
		AND	CodQuote = @Original_CodQuote
		AND	QuoteRev = @Original_QuoteRev

COMMIT tran

RETURN
GO
PRINT N'Creating [dbo].[stp_TI_upsert]...';


GO


-- =============================================
-- Author:		S.E. Locatelli
-- Create date: 2013.12.20
-- Description:	Crea TabImb (tabella imballi)
--              NON SERVE PIU' le due tabelle sono state inglobate in Package2/Item/Client
-- =============================================
CREATE PROCEDURE [dbo].[stp_TI_upsert]
(
	@dateFrom	DATETIME, -- data da cui iniziare a caricare
	@dateTo		DATETIME  -- data fino a cui caricare
) 
AS
BEGIN

    SET XACT_ABORT ON;
	BEGIN TRAN

		SET NOCOUNT ON;

		-- svuoto tabella...
		TRUNCATE TABLE TabImbArt
		TRUNCATE TABLE TabImbGrp
		
		-- riempio di nuovo valori x articolo!
		INSERT INTO TabImbArt
		SELECT 			
				dd.CodItem as KeyA
			  , ROUND(SUM(QtyOUT* QuotaMan) / CASE WHEN SUM(QtyOUT) = 0 THEN 1 ELSE SUM(QtyOUT) END,0) as NumImb
			  , SUM(QtyOUT) AS TotOut
			  , SUM(Duration) AS Durata
		FROM	ProductionLog pl INNER JOIN DiesDet dd ON pl.CodDies=dd.CodDies
		WHERE	pl.ProcessNum = '04'
			AND pl.okPr = 1 AND pl.okQM = 1
			AND	pl.EventStart BETWEEN @dateFrom AND @dateTo
		GROUP BY dd.CodItem
		ORDER BY dd.CodItem

		
		-- riempio di nuovo valori x gruppo imballo!
		INSERT INTO TabImbGrp
		SELECT 			
				pl.CodPackag
			  , ROUND(SUM(QtyOUT* QuotaMan) / CASE WHEN SUM(QtyOUT) = 0 THEN 1 ELSE SUM(QtyOUT) END,0) as NumImb
			  , SUM(QtyOUT) AS TotOut
			  , SUM(Duration) AS Durata
		FROM	ProductionLog pl INNER JOIN DiesDet dd ON pl.CodDies=dd.CodDies
		WHERE	pl.ProcessNum = '04'
			AND pl.okPr = 1 AND pl.okQM = 1
			AND	pl.EventStart BETWEEN @dateFrom AND @dateTo
		GROUP BY pl.CodPackag
		ORDER BY pl.CodPackag
	
		-- salvo nuova revisione dati di produzione...
		INSERT INTO RevHistory
		SELECT	'P', ISNULL(MAX(RevNum),0) + 1, GETDATE(), 'Aggiornamento dati di produzione x fase 04 ' + CONVERT(NVARCHAR(20), @dateFrom, 120) + ' --> ' +CONVERT(NVARCHAR(20), @dateTo, 120)
		FROM	RevHistory
		WHERE	RevType = 'P'

	COMMIT TRAN

END
GO
PRINT N'Creating [dbo].[stp_TPS_upsert]...';


GO


-- =============================================
-- Author:		S.E. Locatelli
-- Create date: 2013.12.13
-- Description:	Crea TabProdSc (tabella produttività/scarti)
-- =============================================
CREATE PROCEDURE [dbo].[stp_TPS_upsert]
(
	@dateFrom	DATETIME, -- data da cui iniziare a caricare
	@dateTo		DATETIME  -- data fino a cui caricare
) 
AS
BEGIN

    SET XACT_ABORT ON;
	BEGIN TRAN

		SET NOCOUNT ON;

		-- svuoto tabella...
		TRUNCATE TABLE TabProdSc

		-- riempio di nuovo valori! chiave AMIL
		INSERT INTO TabProdSc
        SELECT 			
			  dd.CodItem + '-' + pl.RawMat + '-' + pl.CodPlant + '-' + CAST(dd.HoleNum AS NVARCHAR(19)) AS KeyAMIL
			, dd.CodDiesGroup
			, dd.CodItem + '-' + pl.RawMat AS KeyAM
			,  dd.CodItem, pl.RawMat, pl.CodPlant, dd.HoleNum
			, 0             AS NumSMED -- numero cambi, da sistemare...
			, SUM(QtyOUT)   AS KgTeorici
			, SUM(QtyIN)    AS KgLordi
			, SUM(Duration) AS Durata
		FROM	ProductionLog pl 
            INNER JOIN DiesDet dd ON pl.CodDies=dd.CodDies
		WHERE	pl.ProcessNum='01' and pl.EventType=1
			AND pl.okPr = 1 
            AND pl.okSc = 1
			AND	pl.EventStart BETWEEN @dateFrom AND @dateTo
		GROUP BY dd.CodItem, pl.RawMat, dd.CodDiesGroup, pl.CodPlant, dd.HoleNum
		ORDER BY dd.CodItem, pl.RawMat, dd.CodDiesGroup, SUM(QtyOUT) DESC
	    
		-- riempio di nuovo valori! chiave CMIL
        INSERT INTO TabProdSc
        SELECT 			
			  id.CodItemGroup + '-' + pl.RawMat + '-' + pl.CodPlant + '-' + CAST(dd.HoleNum AS NVARCHAR(19)) AS KeyAMIL
			, dd.CodDiesGroup
			, id.CodItemGroup + '-' + pl.RawMat AS KeyAM
			,  id.CodItemGroup, pl.RawMat, pl.CodPlant, dd.HoleNum
			, 0             AS NumSMED -- numero cambi, da sistemare...
			, SUM(QtyOUT)   AS KgTeorici
			, SUM(QtyIN)    AS KgLordi
			, SUM(Duration) AS Durata
		FROM	ProductionLog pl INNER JOIN DiesDet dd ON pl.CodDies=dd.CodDies
            INNER JOIN ItemDet id ON dd.CodItem = id.CodItem
		WHERE	pl.ProcessNum='01' and pl.EventType=1
			AND pl.okPr = 1 AND pl.okSc = 1
			AND	pl.EventStart BETWEEN @dateFrom AND @dateTo
		GROUP BY id.CodItemGroup, pl.RawMat, dd.CodDiesGroup, pl.CodPlant, dd.HoleNum
		ORDER BY id.CodItemGroup, pl.RawMat, dd.CodDiesGroup, SUM(QtyOUT) DESC


	    -- calcolo cambi SMED

		-- con cte
		; WITH cteCambiPre
		AS
		(
			SELECT 
						ROW_NUMBER() OVER(ORDER BY CodPlant, EventStart ASC) AS Row,
						CodPlant, RawMat, EventStart, ProcessNum, CodDies, CodClient, OrderNum, BatchNum
			FROM		ProductionLog pl
			WHERE		pl.ProcessNum='01' and pl.EventType=1
				AND		pl.okPr = 1 AND pl.okSc = 1
				AND		pl.EventStart BETWEEN @dateFrom AND @dateTo
		)
		, cteCambi 
		AS
		(
            -- PARTE AMIL
			SELECT    dd.CodItem + '-' + a.RawMat + '-' + a.CodPlant + '-' + CAST(dd.HoleNum AS NVARCHAR(19)) as KeyAMIL
					, dd.CodDiesGroup
					, a.*
					--, b.Row
					--, ISNULL(b.Row, 0) AS Cambio   -- se 0 c'è cambio
					--, CASE ISNULL(b.Row, 0) WHEN 0 THEN 1 ELSE 0 END AS Cambio2
					, CASE ISNULL(b.Row, 0) WHEN 0 THEN 1 ELSE 0 END AS Cambio2
			FROM cteCambiPre AS a
			LEFT JOIN cteCambiPre AS b 
				ON a.Row-1 = b.Row 
				   AND a.CodPlant = b.CodPlant AND a.CodDies = b.CodDies
			INNER JOIN DiesDet dd ON a.CodDies=dd.CodDies
					WHERE b.Row IS NULL                     -- se voglio vedere solo i cambi
			--ORDER BY a.CodPlant, a.EventStart

            UNION
            -- PARTE CMIL
			SELECT    id.CodItemGroup + '-' + a.RawMat + '-' + a.CodPlant + '-' + CAST(dd.HoleNum AS NVARCHAR(19)) as KeyAMIL
					, dd.CodDiesGroup
					, a.*
					--, b.Row
					--, ISNULL(b.Row, 0) AS Cambio   -- se 0 c'è cambio
					--, CASE ISNULL(b.Row, 0) WHEN 0 THEN 1 ELSE 0 END AS Cambio2
					, CASE ISNULL(b.Row, 0) WHEN 0 THEN 1 ELSE 0 END AS Cambio2
			FROM cteCambiPre AS a
			LEFT JOIN cteCambiPre AS b 
				ON a.Row-1 = b.Row 
				   AND a.CodPlant = b.CodPlant AND a.CodDies = b.CodDies
			INNER JOIN DiesDet dd ON a.CodDies=dd.CodDies
                INNER JOIN ItemDet id ON dd.CodItem = id.CodItem
					WHERE b.Row IS NULL                     -- se voglio vedere solo i cambi
			--ORDER BY a.CodPlant, a.EventStart
		)
		UPDATE	tps
		SET		NumSMED = cc.NumSMED
		FROM	TabProdSc tps
		INNER JOIN (
			SELECT KeyAMIL, CodDiesGroup, SUM(Cambio2) as NumSMED 
			FROM cteCambi
			GROUP BY KeyAMIL, CodDiesGroup
			--ORDER BY KeyAMIL, CodDiesGroup
			) AS cc
			ON tps.KeyAMIL= cc.KeyAMIL AND tps.CodDiesGroup = cc.CodDiesGroup



--		-- altro metodo, forse + veloce...
--		DROP TABLE test

--        CREATE TABLE [dbo].[test](
--	        [Row] [bigint] IDENTITY(1,1) NOT NULL,
--	        [CodPlant] [nvarchar](50) NOT NULL,
--	        [EventStart] [datetime] NOT NULL,
--	        [ProcessNum] [nvarchar](50) NOT NULL,
--	        [CodDies] [nvarchar](50) NOT NULL,
--	        [CodClient] [nvarchar](50) NOT NULL,
--	        [OrderNum] [nvarchar](50) NOT NULL,
--	        [BatchNum] [nvarchar](50) NOT NULL,
--         CONSTRAINT [PK_test] PRIMARY KEY CLUSTERED 
--        (
--	        [Row] ASC
--        )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
--        ) ON [PRIMARY]


--        INSERT INTO TEST
--        SELECT CodPlant, EventStart, ProcessNum, CodDies, CodClient, OrderNum, BatchNum
--        FROM		ProductionLog pl
--        WHERE		pl.ProcessNum='01' and pl.EventType=1 
--        ORDER BY	CodPlant, EventStart

----     SELECT * FROM Test

--        SELECT    a.*
--                , b.Row
--                , ISNULL(b.Row, 0) AS Cambio   -- se 0 c'è cambio
--                , CASE ISNULL(b.Row, 0) WHEN 0 THEN 1 ELSE 0 END AS Cambio2
--        FROM test AS a
--        LEFT JOIN test AS b 
--            ON a.Row - 1 = b.Row                                            -- aggancio record precedente
--               AND a.CodPlant = b.CodPlant AND a.CodDies = b.CodDies
--		WHERE b.Row IS NULL                                                 -- solo i cambi
--        ORDER BY	a.CodPlant, a.EventStart



		-- salvo nuova revisione dati di produzione...
		INSERT INTO RevHistory
		SELECT	'P', ISNULL(MAX(RevNum),0) + 1, GETDATE(), 'Aggiornamento dati di produzione fase 01 ' + CONVERT(NVARCHAR(20), @dateFrom, 120) + ' --> ' +CONVERT(NVARCHAR(20), @dateTo, 120)
		FROM	RevHistory
		WHERE	RevType = 'P'

	COMMIT TRAN

END
GO
PRINT N'Creating [dbo].[stp_VSItem_SearchLike]...';


GO
-- =============================================
-- Author:		S.E. Locatelli
-- Create date: 2014.02.18
-- Description:	Ricerca items
-- =============================================
CREATE PROCEDURE [dbo].stp_VSItem_SearchLike
(
	@value NVARCHAR(50)
)

AS
SET NOCOUNT ON;

SELECT value
	,label
FROM v_selItems
WHERE (value LIKE '%' + @value + '%')
	OR (label LIKE '%' + @value + '%')
ORDER BY value
GO
PRINT N'Creating [dbo].[stp_QSP_upsert]...';


GO
-- =============================================
-- Author:		Steamware - S.E.L.
-- Create date: 2014.05.16
-- Description:	update di un record in QL (Full) TIPO SIMULAZIONE e poi aggiorna a cascata
-- =============================================
create PROCEDURE [dbo].[stp_QSP_upsert]
(
    @QuoteType  CHAR(1)         = 'S',
    @CodQuote	BIGINT          = 0 ,
    @QuoteRev	INT             = 0 ,
    @NomePar	NVARCHAR(50)    = '' ,
    @ValPar     NVARCHAR(50)    = ''
)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    
    -- variabili
    DECLARE @trovati INT = 0

    -- inserisco CodDiesGroup
    SELECT  @trovati = COUNT(*)
    FROM    QuoteSimPar
    WHERE   QuoteType       = @QuoteType
	        AND CodQuote    = @CodQuote
	        AND QuoteRev    = @QuoteRev
            AND NomePar     = @NomePar
    IF(@trovati = 0)
        BEGIN
            INSERT INTO QuoteSimPar(QuoteType, CodQuote, QuoteRev, NomePar, ValPar)
            VALUES(@QuoteType, @CodQuote, @QuoteRev, @NomePar, @ValPar)
        END
    ELSE
        BEGIN
            UPDATE  QuoteSimPar
            SET     ValPar      = @ValPar
            WHERE   QuoteType   = @QuoteType
	            AND CodQuote    = @CodQuote
	            AND QuoteRev    = @QuoteRev
                AND NomePar     = @NomePar
        END
END
GO
PRINT N'Creating [dbo].[stp_RMD_getByKey]...';


GO
CREATE PROCEDURE [dbo].stp_RMD_getByKey
(
	@RawMat nvarchar(50)
)
AS
	SET NOCOUNT ON;
SELECT        RawMat, ProcCost, ProcYield, CSR, SSR, SSVA, SSVR, ExtraMatCost, ExtraServCost
FROM            RawMatDet
WHERE        (RawMat = @RawMat)
GO
PRINT N'Creating [dbo].[stp_RPT_insertNew]...';


GO

-- =============================================
-- Author:		Steamware
-- Create date: 2014.04.28
-- Description:	insert record di stampa
-- =============================================
CREATE PROCEDURE [dbo].[stp_RPT_insertNew]
(
	@Ticket		INT,
	@Report		NVARCHAR(50),
	@Chiave		NVARCHAR(250),
	@UserReq	NVARCHAR(50),
	@DataReq	DATETIME,
	@deleteOld	BIT = 0
)
AS

SET NOCOUNT OFF;

SET XACT_ABORT ON;
BEGIN TRAN

	-- se richiesto elimino record vecchi (utile x togliere segnaposto iniziale)
	IF(@deleteOld = 1)
	BEGIN
		DELETE FROM ReportPrintTicket WHERE Ticket = @Ticket
	END

	INSERT INTO ReportPrintTicket (Ticket, Report, Chiave, UserReq, DataReq)
	VALUES (@Ticket, @Report, @Chiave, @UserReq, @DataReq)

COMMIT TRAN
GO
PRINT N'Creating [dbo].[stp_RPT_reserveTicket]...';


GO

-- =============================================
-- Author:		Steamware
-- Create date: 2014.04.28
-- Description:	riserva un record per insert richiesta di stampa
-- =============================================
CREATE PROCEDURE [dbo].[stp_RPT_reserveTicket]
(
	@Report nvarchar(50),
	@UserReq nvarchar(50)

)
AS
SET NOCOUNT OFF;

DECLARE   @Ticket int = 0
		, @Chiave nvarchar(250) = '-'
		, @DataReq datetime = GETDATE()

SET XACT_ABORT ON;
BEGIN TRAN

	SELECT	@Ticket = MAX(Ticket)
	FROM	ReportPrintTicket

	SET		@Ticket = ISNULL(@Ticket, 0) + 1

	INSERT INTO [dbo].[ReportPrintTicket] ([Ticket], [Report], [Chiave], [UserReq], [DataReq])
	VALUES (@Ticket, @Report, @Chiave, @UserReq, @DataReq)

COMMIT TRAN
	
SELECT	Ticket, Report, Chiave, UserReq, DataReq, DataPrint 
FROM	ReportPrintTicket 
WHERE	Ticket = @Ticket
GO
PRINT N'Creating [dbo].[stp_SC2C_countRemaining]...';


GO

-- =============================================
-- Author:		Steamware
-- Mod. date:   2014.05.27
-- Description:	conteggio StandardCostList ancora da processare
-- =============================================
CREATE PROCEDURE [dbo].[stp_SC2C_countRemaining]
AS

DECLARE @Date AS SMALLDATETIME = CONVERT(SMALLDATETIME,CONVERT(CHAR(8), GETDATE(), 112))

SELECT COUNT(*) as RecordsIn
FROM dbo.CostList 
WHERE DateList = @Date AND QuoteType = 'C' AND CodQuote = 0

RETURN
GO
PRINT N'Creating [dbo].[stp_SC2C_deleteForDate]...';


GO
-- =============================================
-- Author:		Steamware
-- Mod. date:   2014.05.29
-- Description:	cancellazione Cost List per data
-- =============================================
CREATE PROCEDURE [dbo].[stp_SC2C_deleteForDate]
    @Date SMALLDATETIME
AS
BEGIN

    SET NOCOUNT ON;

    DECLARE @CodQuoteDateMin BIGINT,
            @CodQuoteDateMax BIGINT;

    SET @Date            = CONVERT(SMALLDATETIME,CONVERT(CHAR(8), @Date, 112))
    SET @CodQuoteDateMin = CONVERT( BIGINT, ( RIGHT(YEAR(@Date),2) + dbo.f_padLeft(MONTH(@Date), 2,'0') + dbo.f_padLeft(DAY(@Date), 2,'0') + dbo.f_padLeft(0, 8,'0') ) )
    SET @CodQuoteDateMax = CONVERT( BIGINT, ( RIGHT(YEAR(@Date),2) + dbo.f_padLeft(MONTH(@Date), 2,'0') + dbo.f_padLeft(DAY(@Date), 2,'0') + dbo.f_padLeft(9, 8,'9') ) )

    -- cancello i dati di carico
    DELETE FROM dbo.CostList  WHERE DateList = @Date AND QuoteType = 'C'

    DELETE FROM dbo.QuoteOC      WHERE QuoteType = 'C' AND CodQuote >= @CodQuoteDateMin AND CodQuote <= @CodQuoteDateMax
    DELETE FROM dbo.QuoteParam   WHERE QuoteType = 'C' AND CodQuote >= @CodQuoteDateMin AND CodQuote <= @CodQuoteDateMax
    DELETE FROM dbo.QuoteWorkExt WHERE QuoteType = 'C' AND CodQuote >= @CodQuoteDateMin AND CodQuote <= @CodQuoteDateMax
    DELETE FROM dbo.QuoteWorkInt WHERE QuoteType = 'C' AND CodQuote >= @CodQuoteDateMin AND CodQuote <= @CodQuoteDateMax
    DELETE FROM dbo.QuoteRM      WHERE QuoteType = 'C' AND CodQuote >= @CodQuoteDateMin AND CodQuote <= @CodQuoteDateMax
    DELETE FROM dbo.QuoteList    WHERE QuoteType = 'C' AND CodQuote >= @CodQuoteDateMin AND CodQuote <= @CodQuoteDateMax   
    DELETE FROM dbo.QuoteFull_C  WHERE QuoteType = 'C' AND CodQuote >= @CodQuoteDateMin AND CodQuote <= @CodQuoteDateMax

    -- RIPULISCO TUTTO 
    -- TRUNCATE TABLE CostList
    -- TRUNCATE TABLE dbo.QuoteFull_C

RETURN

END
GO
PRINT N'Creating [dbo].[stp_QLF_getLast]...';


GO
-- =============================================
-- Author:		Steamware - S.E.L.
-- Create date: 2014.04.17
-- Description:	recupera ultimo record del tipo richiesto
-- =============================================
create PROCEDURE [dbo].[stp_QLF_getLast]
AS

SELECT	TOP 1 * 
FROM	v_QuoteFull_Q
ORDER BY	CodQuote DESC

RETURN
GO
PRINT N'Creating [dbo].[stp_QLF_getMinMax]...';


GO
-- =============================================
-- Author:		Steamware - S.E.L.
-- Create date: 2014.04.23
-- Description:	recupera record min/max per qta batch dato intervallo di analisi
-- =============================================
CREATE PROCEDURE [dbo].[stp_QLF_getMinMax]
(
	@DateMin	INT, -- formato aammgg
	@DateMax	INT  -- formato aammgg
)
AS

WITH cteMin AS
(
SELECT	TOP 1 * 
FROM	v_QuoteFull_Q
WHERE	CodQuote BETWEEN @DateMin AND @DateMax
ORDER BY BatchQty 
)
, cteMax AS
(
SELECT	TOP 1 * 
FROM	v_QuoteFull_Q
WHERE	CodQuote BETWEEN @DateMin AND @DateMax
ORDER BY BatchQty DESC
)

SELECT * FROM cteMin
UNION
SELECT * FROM cteMax

RETURN
GO
PRINT N'Creating [dbo].[stp_QLF_revHist]...';


GO
-- =============================================
-- STORED PROCEDURE stp_QLF_revHist
--
-- Author:		Steamware
-- Create date: 2014.04.29
-- Description:	Recupera tutte le revisioni di un offerta
-- =============================================
create PROCEDURE stp_QLF_revHist
(
	  @QuoteType CHAR(1) = 'Q'
	, @CodQuote	BIGINT = 0
)
AS
SET NOCOUNT ON

-- calcolo con aggiunta campi sommati...
SELECT	vq.*	
FROM	v_QuoteFull_Q vq
WHERE	QuoteType	= @QuoteType
	AND CodQuote	= @CodQuote
ORDER BY QuoteRev DESC

RETURN
GO
PRINT N'Creating [dbo].[stp_QLR_getByDate]...';


GO
-- =============================================
-- Author:		Steamware
-- Mod. date:   2014.05.27
-- Description:	elaborazione OrdersHist
-- =============================================
CREATE PROCEDURE [dbo].[stp_QLR_getByDate]
(
    @DataRif INT
)
AS
BEGIN

SET NOCOUNT ON;

SELECT * 
FROM v_StdCostList
WHERE DataRif = @DataRif

END
RETURN
GO
PRINT N'Creating [dbo].[stp_checkOffers4Item]...';


GO
-- =============================================
-- Author:		Steamware
-- Create date: 2014.05.11
-- Description:	elenco dati produzione x item indicato
-- =============================================
CREATE PROCEDURE dbo.stp_checkOffers4Item (@CodItem NVARCHAR(50) = '')
AS
SELECT rmd.RawMat
	, ISNULL(@CodItem,'-') AS CodItem
	, COUNT(pl.EventStart) AS numRec
FROM RawMatDet rmd
LEFT JOIN (
	SELECT pl.EventStart
		, pl.RawMat
	FROM ProductionLog pl
	INNER JOIN DiesDet dd
		ON pl.CodDies = dd.CodDies
	WHERE dd.CodItem = @CodItem
		AND ISNULL(pl.RawMat, '') <> ''
	) AS pl
	ON rmd.RawMat = pl.RawMat
WHERE ISNULL(rmd.RawMat, '') <>''
GROUP BY rmd.RawMat
ORDER BY rmd.RawMat

RETURN
GO
PRINT N'Creating [dbo].[stp_getDataCodPackag]...';


GO
-- =============================================
-- Author:		G.A.R.
-- Mad. date:   2014-06-06
-- Description:	Ritorna il package e i dati associati dove presenti
--              sostituisce la relativa funzione UDF f_getDataCodPackag
-- =============================================
CREATE PROCEDURE [stp_getDataCodPackag] 

	@CodItem	NVARCHAR(50),
	@CodClient	NVARCHAR(50),
    -- output variable
	@CodPackag      NVARCHAR(50)    OUTPUT,
	@TotQta         DECIMAL(18, 3)  OUTPUT,
	@Weight         DECIMAL(18, 6)  OUTPUT,
	@Tare           DECIMAL(18, 6)  OUTPUT,
	@NumImb         DECIMAL(9, 6)   OUTPUT,
	@Durata         DECIMAL(18, 6)  OUTPUT,
	@LivPackag      NVARCHAR(50)    OUTPUT,
	@LivPackagDet   NVARCHAR(50)    OUTPUT
AS
BEGIN

	SET NOCOUNT ON;
    SET XACT_ABORT ON;

	IF EXISTS ( SELECT * FROM dbo.Package2ItemClient WHERE CodClient = @CodClient AND CodItem = @CodItem)
    	-- primo tentativo: cerco il package dato SIA cliente che ITEM
		BEGIN
			SELECT TOP 1 @CodPackag = CodPackag, @TotQta = TotQta, @Weight = Weight, @Tare = Tare, @NumImb = NumImb, @Durata = Durata
                        ,@LivPackag = 'Item-Client-Package' , @LivPackagDet = @CodItem + '-' + @CodClient + '-' + CodPackag
            FROM dbo.Package2ItemClient 
            WHERE CodClient = @CodClient AND CodItem = @CodItem
			ORDER BY TotQta DESC
		END
	ELSE IF EXISTS ( SELECT * FROM Package2Item WHERE CodItem = @CodItem  )
		-- secondo tentativo: se non lo trovo cerco per SOLO ITEM
		BEGIN
			SELECT TOP 1 @CodPackag = CodPackag, @TotQta = TotQta, @Weight = Weight, @Tare = Tare, @NumImb = NumImb, @Durata = Durata
                        ,@LivPackag = 'Item-Package', @LivPackagDet = @CodItem + '-' + CodPackag
            FROM dbo.Package2Item WHERE CodItem = @CodItem
			ORDER BY TotQta DESC
		END
    ELSE
		-- secondo tentativo: se non lo trovo cerco per SOLO ITEM
		BEGIN
			SELECT TOP 1 @CodPackag = CodPackag, @TotQta = TotQta, @Weight = Weight, @Tare = Tare, @NumImb = NumImb, @Durata = Durata
                         ,@LivPackag = 'Package', @LivPackagDet = CodPackag
            FROM dbo.Package2 WHERE CodPackag = 0
		END
END

RETURN
GO
PRINT N'Creating [dbo].[stp_OH_countRemaining]...';


GO
-- =============================================
-- Author:		Steamware
-- Mod. date:   2014.05.27
-- Description:	conteggio OrdersHist ancora da processare
-- =============================================
CREATE PROCEDURE dbo.stp_OH_countRemaining
AS


SELECT COUNT(*) as RecordsIn
FROM dbo.OrdersHist
WHERE CodQuote = 0

RETURN
GO
PRINT N'Creating [dbo].[stp_PL_getByListLingua]...';


GO
-- =============================================
-- Author:		Steamware
-- Mod date: 2014.05.23
-- Description:	elenco calori x picklist data lingua e CodList
-- =============================================
CREATE PROCEDURE [dbo].[stp_PL_getByListLingua]
(
    @CodList		NVARCHAR(50) = '',
    @Lingua			NVARCHAR(3) = 'IT'
)
AS
SET NOCOUNT ON

SELECT	pl.Value, ISNULL(v.Traduzione, '_'+pl.Lemma+'_') as Label
FROM	PickList pl
	LEFT OUTER JOIN Vocabolario v ON pl.Lemma = v.Lemma
WHERE	pl.CodList = @CodList
	AND	ISNULL(v.Lingua, @Lingua) = @Lingua
ORDER BY	NumOrd

RETURN
GO
PRINT N'Creating [dbo].[stp_QFC_creaListino]...';


GO



-- =============================================
-- STORED PROCEDURE stp_QFC_creaListino
--
-- Author:		Steamware
-- Mod date:    2014.05.26
-- Description:	crea un nuovo listino di costi
-- =============================================
CREATE PROCEDURE [dbo].[stp_QFC_creaListino]
(
	@RawMatCost DECIMAL(18,6)   = 2,
	@BatchQty INT               = 1000
)
AS

SET NOCOUNT ON 

-- questo è l'elenco delle cose da processare, in temp table / Cte x "scorrere" tutto?
SELECT DISTINCT 

      CONVERT(CHAR(8), GETDATE(), 112)      AS DateList
	, die.CodItem                           AS CodItem
	, CASE  WHEN pl.RawMat = ''            -- al momento li escludo perchè poi non ho dati sugli scarti
		    THEN '6060'
		    ELSE pl.RawMat
	  END                                   AS RawMat
	, @RawMatCost                           AS RawMatCost
    , rm.ExtraMatCost                       AS RawMatExtraCost
	, @BatchQty                             AS batchQty
	, 'EXW'                                 AS CodInco

--	  'C'                   AS QuoteType
--	, ''                    AS CodClient   --'' / '05000000001' in alternativa come default

FROM dbo.DiesDet AS die

INNER JOIN dbo.ProductionLog AS pl
	ON die.CodDies = pl.CodDies

INNER JOIN dbo.RawMatDet AS rm
	ON pl.RawMat = rm.RawMat

INNER JOIN dbo.TabProdSc AS sc                      -- escludo record che non hanno dati di scarto produzione
    ON sc.KeyAM = ( die.CodItem + '-' + pl.RawMat)  

WHERE ( pl.RawMat <> '' AND pl.RawMat IS NOT NULL ) -- escludo righe di produzione senza RawMat ( es. fermi o altro )
--   AND ( die.ActLife <> 0 )                         -- escludo matrici senza dati ( es. vecchie matrici senza dati attuali o nuove che non hanno ancora prodotto )

--AND die.CodItem = '3DI05194'
ORDER BY die.CodItem

RETURN
GO
PRINT N'Creating [dbo].[stp_QL_delete]...';


GO


-- =============================================
-- Author:		Steamware
-- Create date: 2013.01.23
-- Description:	elimina record QuoteList
-- =============================================
CREATE PROCEDURE [dbo].[stp_QL_delete]
(
    @QuoteType_orig	CHAR(1) = 'Q',
    @CodQuote_orig	BIGINT	= 0,
    @QuoteRev_orig	INT		= 0
)
AS

SET XACT_ABORT ON;
BEGIN TRAN


    DELETE
    FROM	QuoteFull_Q
    WHERE	QuoteType   = @QuoteType_orig
        AND	CodQuote    = @CodQuote_orig
        AND	QuoteRev    = @QuoteRev_orig


    DELETE
    FROM	QuoteFull_S
    WHERE	QuoteType   = @QuoteType_orig
        AND	CodQuote    = @CodQuote_orig
        AND	QuoteRev    = @QuoteRev_orig

    DELETE
    FROM	QuoteFull_R
    WHERE	QuoteType   = @QuoteType_orig
        AND	CodQuote    = @CodQuote_orig
        AND	QuoteRev    = @QuoteRev_orig

    DELETE
    FROM	QuoteWorkExt
    WHERE	QuoteType   = @QuoteType_orig
        AND	CodQuote    = @CodQuote_orig
        AND	QuoteRev    = @QuoteRev_orig

    DELETE
    FROM	QuoteWorkInt
    WHERE	QuoteType   = @QuoteType_orig
        AND	CodQuote    = @CodQuote_orig
        AND	QuoteRev    = @QuoteRev_orig
        
    DELETE
    FROM	QuoteOC
    WHERE	QuoteType   = @QuoteType_orig
        AND	CodQuote    = @CodQuote_orig
        AND	QuoteRev    = @QuoteRev_orig

    DELETE
    FROM	QuoteParam
    WHERE	QuoteType   = @QuoteType_orig
        AND	CodQuote    = @CodQuote_orig
        AND	QuoteRev    = @QuoteRev_orig

    DELETE
    FROM	QuoteRM
    WHERE	QuoteType   = @QuoteType_orig
        AND	CodQuote    = @CodQuote_orig
        AND	QuoteRev    = @QuoteRev_orig

    DELETE
    FROM	QuoteList
    WHERE	QuoteType   = @QuoteType_orig
        AND	CodQuote    = @CodQuote_orig
        AND	QuoteRev    = @QuoteRev_orig

COMMIT TRAN


RETURN
GO
PRINT N'Creating [dbo].[stp_QLF_Delete]...';


GO
-- =============================================
-- Author:		Steamware - S.E.L.
-- Create date: 2014.04.16
-- Description:	elimina un record in QL (Full) e in tabelle connesse
-- =============================================
create PROCEDURE [dbo].[stp_QLF_Delete]
(
    @Original_QuoteType CHAR(1) = 'Q',
    @Original_CodQuote	BIGINT = 0,
    @Original_QuoteRev	INT = 0
)
AS

SET XACT_ABORT ON;
BEGIN TRAN

	-- elimino da QuoteFull_Q
	DELETE
	FROM QuoteFull_Q
    WHERE	QuoteType = @Original_QuoteType
        AND CodQuote = @Original_CodQuote
        AND QuoteRev = @Original_QuoteRev
		
	-- elimino da QuoteFull_S
	DELETE
	FROM QuoteFull_S
    WHERE	QuoteType = @Original_QuoteType
        AND CodQuote = @Original_CodQuote
        AND QuoteRev = @Original_QuoteRev        

	-- elimino da QuoteWorkExt
	DELETE
	FROM QuoteWorkExt
    WHERE	QuoteType = @Original_QuoteType
        AND CodQuote = @Original_CodQuote
        AND QuoteRev = @Original_QuoteRev

	-- elimino da QuoteWorkInt
	DELETE
	FROM QuoteWorkInt
    WHERE	QuoteType = @Original_QuoteType
        AND CodQuote = @Original_CodQuote
        AND QuoteRev = @Original_QuoteRev

	-- elimino da QuoteSimPar
	DELETE
	FROM QuoteSimPar
    WHERE	QuoteType = @Original_QuoteType
        AND CodQuote = @Original_CodQuote
        AND QuoteRev = @Original_QuoteRev

	-- elimino da QuoteRM
	DELETE
	FROM QuoteRM
    WHERE	QuoteType = @Original_QuoteType
        AND CodQuote = @Original_CodQuote
        AND QuoteRev = @Original_QuoteRev

	-- elimino da QuoteParam
	DELETE
	FROM QuoteParam
    WHERE	QuoteType = @Original_QuoteType
        AND CodQuote = @Original_CodQuote
        AND QuoteRev = @Original_QuoteRev

	-- elimino da QuoteOC
	DELETE
	FROM QuoteOC
    WHERE	QuoteType = @Original_QuoteType
        AND CodQuote = @Original_CodQuote
        AND QuoteRev = @Original_QuoteRev

	-- elimino da QuoteList
	DELETE
	FROM QuoteList
    WHERE	QuoteType = @Original_QuoteType
        AND CodQuote = @Original_CodQuote
        AND QuoteRev = @Original_QuoteRev

COMMIT TRAN

RETURN
GO
PRINT N'Creating [dbo].[stp_listValues_getValidValuesFilt]...';


GO
-- =============================================
-- STORED stp_getValidValuesFilt
--
-- Author:		S.E.L.
-- Create date: 2011.05.26
-- Description:	gestione selezione dati parametrici
--				con filtro su valore con LIKE
-- =============================================
create PROCEDURE [stp_listValues_getValidValuesFilt] 
(
	@TableName NVARCHAR(50),
	@FieldName NVARCHAR(50),
	@valueLike NVARCHAR(10)
)
AS
BEGIN
	SET NOCOUNT ON;

    SELECT	value, label
    FROM	ListValues
    WHERE	TableName = @TableName
	AND		FieldName = @FieldName
	AND		value	LIKE @valueLike +'%'
	ORDER BY ordinal
END
GO
PRINT N'Creating [dbo].[stp_listValues_getValidValues]...';


GO
-- =============================================
-- STORED stp_getValidValues
--
-- Author:		S.E.L.
-- Create date: 2011.05.26
-- Description:	gestione selezione dati parametrici
-- =============================================
create PROCEDURE [stp_listValues_getValidValues] 
(
	@TableName NVARCHAR(50),
	@FieldName NVARCHAR(50)
)
AS
BEGIN
	SET NOCOUNT ON;

    SELECT	value, label
    FROM	ListValues
    WHERE	TableName = @TableName
	AND		FieldName = @FieldName
	ORDER BY ordinal
END
GO
PRINT N'Creating [dbo].[stp_listValues_getByTable]...';


GO
/***************************************
* STORED stp_listValues_getByTable
*
* ottiene elenco campi data Table
*
* Steamware, S.E.L.
* mod: 2014.08.04
*
****************************************/
create PROCEDURE [stp_listValues_getByTable]
(
	@TableName	NVARCHAR(50)
)
AS

	SELECT		* 
	FROM		ListValues
	WHERE		TableName = @TableName
	ORDER BY	ordinal
	
RETURN
GO
PRINT N'Creating [dbo].[stp_QL_fullDataCount]...';


GO
-- =============================================
-- Author:		Steamware
-- Mod date: 2014.05.23
-- Description:	conteggio totale record QL
-- =============================================
CREATE PROCEDURE dbo.stp_QL_fullDataCount
(
	  @CodClient	NVARCHAR(50) = ''
	, @CodItem		NVARCHAR(50) = ''
	, @RawMat		NVARCHAR(50) = ''
	, @DataMin		DATETIME
	, @DataMax		DATETIME
	, @qtaMin		INT = 0
	, @qtaMax		INT = 999999
	, @QuoteType	CHAR(1) = '*'
	, @IdxQState	INT = '-1'
	, @search		NVARCHAR(250) = '*'
)
AS
SET NOCOUNT ON

;WITH qfq_filt AS
(
	SELECT	*	
	FROM	v_QuoteFull_Q
	WHERE	ClientName LIKE CASE WHEN @search <> '*' THEN '%'+@search+'%' ELSE ClientName END
		OR	RawMat LIKE CASE WHEN @search <> '*' THEN '%'+@search+'%' ELSE RawMat END
		OR	CodItem LIKE CASE WHEN @search <> '*' THEN '%'+@search+'%' ELSE CodItem END
		OR	CONVERT(NVARCHAR(30), CodQuote) LIKE CASE WHEN @search <> '*' THEN '%'+@search+'%' ELSE CONVERT(NVARCHAR(30), CodQuote) END
)

SELECT COUNT(DISTINCT CodQuote) AS num
FROM qfq_filt vq
WHERE	vq.CodClient = CASE WHEN ISNULL(@CodClient,'') = '' THEN vq.CodClient ELSE @CodClient END
	AND vq.CodItem = CASE WHEN ISNULL(@CodItem,'') = '' THEN vq.CodItem ELSE @CodItem END
	AND vq.RawMat = CASE WHEN ISNULL(@RawMat,'') = '' THEN vq.RawMat ELSE @RawMat END
	AND vq.CodQuote BETWEEN CONVERT(NVARCHAR(30), @DataMin, 12)*10000 AND (CONVERT(NVARCHAR(30), @DataMax, 12) +1 )*10000 
	AND	vq.BatchQty BETWEEN @qtaMin AND @qtaMax
	AND vq.QuoteType = CASE WHEN @QuoteType = '*' THEN vq.QuoteType ELSE @QuoteType END
	AND vq.IdxQState = CASE WHEN @IdxQState = -1 THEN vq.IdxQState ELSE @IdxQState END

RETURN
GO
PRINT N'Creating [dbo].[stp_QL_copyParamS]...';


GO
-- =============================================
-- Author:		Steamware
-- Mod date: 2014.10.22
-- Description:	copia i parametri per una QL tipo Simulazione per casi clone/revisione
-- =============================================
create PROCEDURE [dbo].[stp_QL_copyParamS]
(
	@QuoteType		CHAR(1) = 'Q',
	@QuoteType_orig	CHAR(1) = 'Q',
	@CodQuote		BIGINT	= 0,
	@CodQuote_orig	BIGINT	= 0,
	@QuoteRev		INT		= 0,
	@QuoteRev_orig	INT		= 0
)
AS


IF(@QuoteType_orig = 'S')			
-- se partenza è S duplico dati accessori...
	BEGIN
		INSERT INTO QuoteSimPar(QuoteType, CodQuote, QuoteRev, NomePar, ValPar)
		SELECT  @QuoteType, @CodQuote, @QuoteRev, NomePar, ValPar
		FROM    QuoteSimPar
		WHERE		QuoteType = @QuoteType_orig
				AND	CodQuote = @CodQuote_orig
				AND	QuoteRev = @QuoteRev_orig
	END
ELSE
-- se partenza è Q carico alcuni dati accessori precompilando...
	BEGIN				
		INSERT INTO QuoteSimPar(QuoteType, CodQuote, QuoteRev, NomePar, ValPar)
		SELECT  @QuoteType, @CodQuote, @QuoteRev, Descr, Parameter
		FROM    QuoteParam
		WHERE		QuoteType = @QuoteType_orig
				AND	CodQuote = @CodQuote_orig
				AND	QuoteRev = @QuoteRev_orig
				AND Descr IN ('CodDiesGroup', 'CodPlant')
					
		INSERT INTO QuoteSimPar(QuoteType, CodQuote, QuoteRev, NomePar, ValPar)
		SELECT  @QuoteType, @CodQuote, @QuoteRev, 'DiesTecLife', Parameter
		FROM    QuoteParam
		WHERE		QuoteType = @QuoteType_orig
				AND	CodQuote = @CodQuote_orig
				AND	QuoteRev = @QuoteRev_orig
				AND Descr = 'KgTeo'
					
		INSERT INTO QuoteSimPar(QuoteType, CodQuote, QuoteRev, NomePar, ValPar)
		SELECT  @QuoteType, @CodQuote, @QuoteRev, 'DiesPrice_sim', Parameter
		FROM    QuoteParam
		WHERE		QuoteType = @QuoteType_orig
				AND	CodQuote = @CodQuote_orig
				AND	QuoteRev = @QuoteRev_orig
				AND Descr = 'DiesPrice'
					
		INSERT INTO QuoteSimPar(QuoteType, CodQuote, QuoteRev, NomePar, ValPar)
		SELECT  @QuoteType, @CodQuote, @QuoteRev, 'CodPackag', CodPackag
		FROM    QuoteRM
		WHERE		QuoteType = @QuoteType_orig
				AND	CodQuote = @CodQuote_orig
				AND	QuoteRev = @QuoteRev_orig
					
		INSERT INTO QuoteSimPar(QuoteType, CodQuote, QuoteRev, NomePar, ValPar)
		SELECT  @QuoteType, @CodQuote, @QuoteRev, 'NetProd01_sim', NetProd
		FROM    QuoteWorkInt
		WHERE		QuoteType = @QuoteType_orig
				AND	CodQuote = @CodQuote_orig
				AND	QuoteRev = @QuoteRev_orig
				AND	ProcessNum = '01'
							
		INSERT INTO QuoteSimPar(QuoteType, CodQuote, QuoteRev, NomePar, ValPar)
		SELECT  @QuoteType, @CodQuote, @QuoteRev, 'NetProd04_sim', NetProd
		FROM    QuoteWorkInt
		WHERE		QuoteType = @QuoteType_orig
				AND	CodQuote = @CodQuote_orig
				AND	QuoteRev = @QuoteRev_orig
				AND	ProcessNum = '04'
					
		INSERT INTO QuoteSimPar(QuoteType, CodQuote, QuoteRev, NomePar, ValPar)
		SELECT  @QuoteType, @CodQuote, @QuoteRev, 'MSR01_sim', MSR
		FROM    QuoteWorkInt
		WHERE		QuoteType = @QuoteType_orig
				AND	CodQuote = @CodQuote_orig
				AND	QuoteRev = @QuoteRev_orig
				AND	ProcessNum = '01'
					
		INSERT INTO QuoteSimPar(QuoteType, CodQuote, QuoteRev, NomePar, ValPar)
		SELECT  @QuoteType, @CodQuote, @QuoteRev, 'WSR01_sim', WSR
		FROM    QuoteWorkInt
		WHERE		QuoteType = @QuoteType_orig
				AND	CodQuote = @CodQuote_orig
				AND	QuoteRev = @QuoteRev_orig
				AND	ProcessNum = '01'
					
		INSERT INTO QuoteSimPar(QuoteType, CodQuote, QuoteRev, NomePar, ValPar)
		SELECT  @QuoteType, @CodQuote, @QuoteRev, 'DSR_sim', DSR
		FROM    QuoteWorkInt
		WHERE		QuoteType = @QuoteType_orig
				AND	CodQuote = @CodQuote_orig
				AND	QuoteRev = @QuoteRev_orig
				AND	ProcessNum = '04'
	END	

RETURN
GO
PRINT N'Creating [dbo].[stp_TD_upsert]...';


GO

-- =============================================
-- Author:		S.E. Locatelli
-- Create date: 2013.12.17
-- Description:	Crea TabDifett (tabella difettosità)
-- =============================================
CREATE PROCEDURE [dbo].[stp_TD_upsert]
(
	@dateFrom	DATETIME, -- data da cui iniziare a caricare
	@dateTo		DATETIME  -- data fino a cui caricare
) 
AS
BEGIN

    SET XACT_ABORT ON;
	BEGIN TRAN

		SET NOCOUNT ON;

		-- svuoto tabella...
		TRUNCATE TABLE TabDifett

		-- riempio di nuovo valori! chiave AMI
		INSERT INTO TabDifett
		SELECT 			
			  dd.CodItem + '-' + pl.RawMat + '-' + pl.CodPlant as KeyAMI
			, pl.ProcessNum
			, dd.CodItem, pl.RawMat, pl.CodPlant
			, SUM(NumOUT) as TotOUT
			, SUM(NumIN) as TotIn
		FROM	ProductionLog pl INNER JOIN DiesDet dd ON pl.CodDies=dd.CodDies
		WHERE	pl.ProcessNum IN ('02', '04')
			AND pl.okDi = 1
			-- and pl.EventType=1
			AND	pl.EventStart BETWEEN @dateFrom AND @dateTo
		GROUP BY dd.CodItem, pl.RawMat, pl.CodPlant, pl.ProcessNum
		ORDER BY dd.CodItem, pl.RawMat, pl.ProcessNum--, SUM(NumOUT) DESC
	
        -- riempio di nuovo valori! chiave CMI
		INSERT INTO TabDifett
		SELECT 			
			  id.CodItemGroup + '-' + pl.RawMat + '-' + pl.CodPlant as KeyAMI
			, pl.ProcessNum
			, id.CodItemGroup, pl.RawMat, pl.CodPlant
			, SUM(NumOUT) as TotOUT
			, SUM(NumIN) as TotIn
		FROM	ProductionLog pl 
            INNER JOIN DiesDet dd ON pl.CodDies=dd.CodDies
            INNER JOIN ItemDet id ON dd.CodItem = id.CodItem
		WHERE	pl.ProcessNum IN ('02', '04')
			AND pl.okDi = 1
			-- and pl.EventType=1
			AND	pl.EventStart BETWEEN @dateFrom AND @dateTo
		GROUP BY id.CodItemGroup, pl.RawMat, pl.CodPlant, pl.ProcessNum
		ORDER BY id.CodItemGroup, pl.RawMat, pl.ProcessNum--, SUM(NumOUT) DESC
	
		-- salvo nuova revisione dati di produzione...
		INSERT INTO RevHistory
		SELECT	'P', ISNULL(MAX(RevNum),0) + 1, GETDATE(), 'Aggiornamento dati di produzione x fasi 02/03 ' + CONVERT(NVARCHAR(20), @dateFrom, 120) + ' --> ' +CONVERT(NVARCHAR(20), @dateTo, 120)
		FROM	RevHistory
		WHERE	RevType = 'P'

	COMMIT TRAN

END
GO
PRINT N'Creating [dbo].[stp_QL_update]...';


GO
-- =============================================
-- Author:		Steamware
-- Mod. date: 2014.10.21
-- Description:	aggiorna le tabelle QuoteList con i dati selezionati dalla TabProdSc
-- =============================================
CREATE PROCEDURE [dbo].[stp_QL_update]
(
	@QuoteType	CHAR(1) = 'Q',
	@CodQuote	BIGINT	= 0,
	@QuoteRev	INT		= 0
) 
AS
BEGIN

	SET NOCOUNT ON;

	-- dichiaro valori da recuperare
	DECLARE	@strTemp		NVARCHAR(50) = '' --stringa temporanea x variabili "locali"	
		  , @valid			BIT -- bit validità generico totale
		  , @validStep      BIT -- bit validità generico singolo step
		  , @errorScore		INT -- punteggio errori (1 per errore o anche punti diversi x "Peso", da valutare
		  , @CodDiesGroup	NVARCHAR(50) = ''
		  , @CodPlant		NVARCHAR(50) = ''
		  , @CodPlantCMIL	NVARCHAR(50) 
		  , @CodPlantFix	NVARCHAR(50) = ''
		  , @HoleNum		INT

	-- ITEM
	DECLARE @CodItem		NVARCHAR(50) = '' -- cod item
		  , @ItemDescr		NVARCHAR(50) = '' -- descrizione item
		  , @CodifProfilo   NVARCHAR(50) = '' -- Cod. Profilo
		  , @ClasseMerc     NVARCHAR(50) = '' 
		  , @CodClientAssoc NVARCHAR(50) = '' 
		  , @KeyAM			NVARCHAR(50) = ''
		  , @KeyAMI			NVARCHAR(50) = ''
		  , @KeyAMIL		NVARCHAR(50) = ''
		  , @NumSMED		INT = 0 -- numero cambi
		  , @KgTeo			DECIMAL(18, 6) = 0 -- kg totali
		  , @RawMat			NVARCHAR(50)
		  ,	@ProdTeo		DECIMAL(18,6) = 0
		  ,	@ProdTeo_sim	DECIMAL(18,6) = 0   
		  ,	@ScTec			DECIMAL(18,6)
		  ,	@BatchQty		INT
		  ,	@MAC_SC			DECIMAL(18,6)       -- Messa a cento scarto cesoia
		  ,	@MAC_ST			DECIMAL(18,6)       -- Messa a cento scarto tecnico
		  ,	@MAC_IN			DECIMAL(18,6)       -- Messa a cento difettosità all'incestatura
		  ,	@MAC_IM			DECIMAL(18,6)       -- Messa a cento difettosità all'imballo
		  ,	@MAC_SC_sim 	DECIMAL(18,6) = 0   -- Messa a cento scarto cesoia - SIMULAZIONE
		  ,	@MAC_ST_sim 	DECIMAL(18,6) = 0   -- Messa a cento scarto tecnico - SIMULAZIONE
		  ,	@MAC_IN_sim 	DECIMAL(18,6) = 0   -- Messa a cento difettosità all'incestatura - SIMULAZIONE
		  ,	@MAC_IM_sim 	DECIMAL(18,6) = 0   -- Messa a cento difettosità all'imballo - SIMULAZIONE
		  ,	@FCR_sim		DECIMAL(18,6) = 0   -- Messa a cento complessiva - SIMULAZIONE
		  ,	@SSR			DECIMAL(9,6)        -- percentuale vendita rottame
		  ,	@DiesPrice		DECIMAL(9,3)        -- prezzo matrice
          , @NumDiesExaust  INT = 0             -- numero matrici rottamate
		  ,	@DiesEOLife		DECIMAL(9,2)        -- durata matrice CLASSE MATRICE
		  ,	@DiesExpLife	DECIMAL(9,2)        -- durata matrice ARTICOLO
		  ,	@DiesPriceLife	DECIMAL(18,6)       -- Price/Life matrice
		  ,	@DiesByClass	BIT = 0             -- definisce se i dati della matrice siano calcolati puntualmente (0) o per classe (1)
		  ,	@OCF01			DECIMAL(18,6) = 0 -- altri costi di fase 01
		  ,	@VCF01			DECIMAL(18,6) = 0 -- costi variabili di fase 01
		  ,	@VCF04			DECIMAL(18,6) = 0 -- costi variabili di fase 04
		  ,	@SellCostF01	DECIMAL(18,6) = 0 -- costo vendita fase 01
		  ,	@SellCostF04	DECIMAL(18,6) = 0 -- costo vendita fase 04
		  ,	@RefCostF01		DECIMAL(18,6) = 0 -- costo rifusione fase 01 
		  ,	@RefCostF04		DECIMAL(18,6) = 0 -- costo rifusione fase 04
	-- IMBALLO
	DECLARE	@CodPackag		NVARCHAR(50) = '0'  -- codice dell'imballo
		  , @CodClient		NVARCHAR(50) = ''   -- codice cliente
		  , @NumImb			DECIMAL(9,6) = 0    -- num imballatori
		  , @PkgDesc		NVARCHAR(50) = ''   -- descrizione imballo
		  , @PRMWeight		DECIMAL(9,4) = 0    -- peso dell'imballo
		  , @PWeight		DECIMAL(9,4) = 0    -- peso del pacco
		  , @PTare			DECIMAL(9,4) = 0    -- media delal tara di imballo dichiarata
		  , @PCost			DECIMAL(9,6) = 0    -- costo unitario dell'imballo (al kg) 
		  , @PTareStRatio	DECIMAL(9,4) = 0    -- coefficiente di recupero tara/prodotto
		  , @PTotQta        DECIMAL(18,3) = 0   -- Qta Kg Tot Imballati
		  , @PDurata        DECIMAL(18,6) = 0   -- Tempo d'imballaggio
		  , @PLiv           NVARCHAR(50)  = ''  -- Livello Search dati Imballo     
		  , @PLivDett       NVARCHAR(50)  = ''  -- Key Livello Search Dati Imballo
		  ,	@ProdTeoImb		DECIMAL(18,6) = 0   -- produttività SIMULATA imballo
		  ,	@ProdTeoImb_sim	DECIMAL(18,6) = 0   -- produttività SIMULATA imballo
	-- TRASPORTI
	DECLARE	@TranspZone		NVARCHAR(50) = '' -- codice ZONA
		  ,	@TranspCost		DECIMAL(9,6) = 0  -- costo di trasporto
		  ,	@HasTC			INT

	-- PROVVIGIONI
	DECLARE	@Provvig		DECIMAL(9,6) -- provvigione agente
	
	-- default: validità è true!
	SET		@valid = 1
	-- default: error score è nullo
	SET		@errorScore = 0

	-- =================================================
	--   CREAZIONE TEMP TABLE
	-- =================================================

	-- elimino e ricreo #QuoteParam temp table... NON Serve nella stored
	--IF OBJECT_ID('tempdb..#QuoteParam') IS NOT NULL
	--	DROP TABLE #QuoteParam

	CREATE TABLE #Quoteparam
	(
				 Quotetype  CHAR( 1 )           COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
				 Codquote   BIGINT              NOT NULL,
				 Quoterev   INT                 NOT NULL,
				 Nump       INT IDENTITY( 1,1 ) NOT NULL,
				 Processnum NVARCHAR( 50 )      COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
				 Descr      NVARCHAR( 50 )      COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
				 Parameter  NVARCHAR( 100 )     COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL DEFAULT(''),
	--PRIMARY KEY
	--		(	QuoteType ASC, CodQuote ASC, QuoteRev ASC ) WITH  (PAD_INDEX  = ON, FILLFACTOR = 99 )
	);

	-- oppure creo l'indice successivamente
	--CREATE CLUSTERED INDEX #ix_Quoteparam ON #Quoteparam (QuoteType ASC, CodQuote ASC, QuoteRev ASC)
	--WITH (PAD_INDEX  = ON, FILLFACTOR = 100)

	--CREATE STATISTICS [#ix_QuoteType_CodQuote] ON #Quoteparam ([QuoteType], [CodQuote], [QuoteRev])

	-- elimino e ricreo ##QuoteWorkInt temp table...
	--IF OBJECT_ID('tempdb..#QuoteWorkInt') IS NOT NULL 	DROP TABLE #QuoteWorkInt

   CREATE TABLE #QuoteWorkInt
	(
		QuoteType     CHAR(1)   COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
		CodQuote      BIGINT    NOT NULL,
		QuoteRev      INT       NOT NULL,
		NumWI         INT IDENTITY(1,1) NOT NULL,
		ProcessNum    NVARCHAR(50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
		CodPlant      NVARCHAR(50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
		Class01       NVARCHAR(50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL DEFAULT (''),
		Class02       NVARCHAR(50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL DEFAULT (''),
		Class03       NVARCHAR(50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL DEFAULT (''),
		Class04       NVARCHAR(50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL DEFAULT (''),
		Class05       NVARCHAR(50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL DEFAULT (''),
		NetProd       DECIMAL(9, 3) NOT NULL DEFAULT ((0)),
		WSR           DECIMAL(9, 8) NOT NULL DEFAULT ((0)),
		MSR           DECIMAL(9, 8) NOT NULL DEFAULT ((0)),
		DSR           DECIMAL(9, 8) NOT NULL DEFAULT ((0)),
		FC4UG         DECIMAL(9, 6) NOT NULL DEFAULT ((0)),
		VC4UG         DECIMAL(9, 6) NOT NULL DEFAULT ((0)),
		OH4UG         DECIMAL(9, 6) NOT NULL DEFAULT ((0)),
		SC4UG         DECIMAL(9, 6) NOT NULL DEFAULT ((0)),
		-- campi calcolati
		WYR   AS ((1)-WSR),
		MYR   AS ((1)-MSR),
		DYR   AS ((1)-DSR),
		WCR   AS ( CASE WHEN ((1)-WSR)=0 THEN 1 ELSE (1)/((1)-WSR) END ),
		MCR   AS ( CASE WHEN ((1)-MSR)=0 THEN 1 ELSE (1)/((1)-MSR) END ),
		DCR   AS ( CASE WHEN ((1)-DSR)=0 THEN 1 ELSE (1)/((1)-DSR) END ),
		valid BIT NOT NULL DEFAULT((1)),
	)

-- elimino e ricreo #QuoteOC temp table...
--IF OBJECT_ID('tempdb..#QuoteOC') IS NOT NULL DROP TABLE #QuoteOC

	CREATE TABLE #QuoteOC 
	(
		QuoteType   CHAR(1)             COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
		CodQuote    BIGINT              NOT NULL,
		QuoteRev    INT                 NOT NULL,
		NumEx       INT IDENTITY(1,1)   NOT NULL,
		ProcessNum  NVARCHAR(50)        COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL DEFAULT (''),
		CodPlant    NVARCHAR(50)        COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL DEFAULT (''),
		Class01     NVARCHAR(50)        COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL DEFAULT (''),
		Class02     NVARCHAR(50)        COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL DEFAULT (''),
		Class03     NVARCHAR(50)        COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL DEFAULT (''),
		Class04     NVARCHAR(50)        COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL DEFAULT (''),
		Class05     NVARCHAR(50)        COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL DEFAULT (''),
		TotQty      DECIMAL(18, 6)      NOT NULL DEFAULT ((1)),
		TotCost     DECIMAL(18, 6)      NOT NULL DEFAULT ((0)),
		Quota       DECIMAL(18, 6)      NOT NULL DEFAULT ((1)),
		C4UG        AS ( CASE WHEN TotQty= 0 THEN 0 ELSE (TotCost*Quota) / TotQty END ),
		valid       BIT NOT NULL DEFAULT ((1))
	)

	-- ===================================
	--  INIZIO TRANSAZIONE
	-- ===================================
	SET XACT_ABORT ON;
	BEGIN TRAN

        
		---------------------------------------
		-- salvataggio parametri iniziale
		---------------------------------------
        DECLARE @NetProd01_sim  DECIMAL(9,3) = 0 -- prod simulazione fase 01
        DECLARE @NetProd04_sim  DECIMAL(9,3) = 0 -- prod simulazione fase 04
        
        -- cerco la prod netta fase 1 di simulazione...
        SELECT  @NetProd01_sim = CAST(Parameter AS DECIMAL(9,3))
        FROM    dbo.QuoteParam
        WHERE   descr = 'NetProd01_sim'
            AND QuoteType	= @QuoteType
			AND	CodQuote	= @CodQuote
			AND	QuoteRev	= @QuoteRev

        -- cerco la prod netta fase 1 di simulazione...
        SELECT  @NetProd04_sim = CAST(Parameter AS DECIMAL(9,3))
        FROM    dbo.QuoteParam
        WHERE   descr = 'NetProd04_sim'
            AND QuoteType	= @QuoteType
			AND	CodQuote	= @CodQuote
			AND	QuoteRev	= @QuoteRev

        --SELECT @NetProd01_sim as NetProd01_sim, @NetProd04_sim as NetProd04_sim
                
		---------------------------------------
		-- svuotamento iniziale
		---------------------------------------
	
		-- elimino quote PARAMETRI!
		DELETE FROM	dbo.QuoteParam
		WHERE	QuoteType	= @QuoteType
			AND	CodQuote	= @CodQuote
			AND	QuoteRev	= @QuoteRev

		-- elimino lavorazioni ESTERNE!
		DELETE FROM	dbo.QuoteWorkExt
		WHERE	QuoteType	= @QuoteType
			AND	CodQuote	= @CodQuote
			AND	QuoteRev	= @QuoteRev

		-- elimino lavorazioni INTERNE
		DELETE FROM	dbo.QuoteWorkInt
		WHERE	QuoteType	= @QuoteType
			AND	CodQuote	= @CodQuote
			AND	QuoteRev	= @QuoteRev

		-- elimino OtherCosts
		DELETE FROM	dbo.QuoteOC
		WHERE	QuoteType	= @QuoteType
			AND	CodQuote	= @CodQuote
			AND	QuoteRev	= @QuoteRev

		-- se ci sono eccezioni nella tab dell'anagrafico articoli imposto il codPlant desiderato
		SET	@CodPlantFix = ISNULL ( ( SELECT id.CodPlant FROM dbo.ItemDet id 
									  INNER JOIN dbo.QuoteList ql ON id.CodItem = ql.CodItem
									  WHERE ql.QuoteType   = @QuoteType
										AND ql.CodQuote    = @CodQuote
										AND ql.QuoteRev    = @QuoteRev ), '' )

		-- recupero da dati dell'offerta il valore del cliente
		SELECT	@CodClient		= CodClient
		FROM	dbo.QuoteList
		WHERE	QuoteType = @QuoteType AND CodQuote = @CodQuote AND QuoteRev = @QuoteRev
		
		IF (@QuoteType IN ('Q', 'R','C' ) )    -- Quotation, Reddittivity, Cost List
			BEGIN
				-- recupero dati!!
				SELECT	TOP 1 @CodItem	        = ql.CodItem
							, @CodDiesGroup     = tps.CodDiesGroup
							, @CodPlant         = CASE WHEN @CodPlantFix <> '' THEN @CodPlantFix ELSE tps.CodPlant END
							, @HoleNum          = tps.HoleNum
							, @KeyAM	        = ql.KeyAM
							, @KeyAMI	        = ql.KeyAM + '-' + ISNULL(@CodPlant,'0000')
							, @KeyAMIL	        = ql.KeyAM + '-' + ISNULL(@CodPlant,'0000') + '-' + CAST(ISNULL(tps.HoleNum,0) AS NVARCHAR(10))
							, @ProdTeo	        = tps.ProdTeo
							, @ScTec	        = tps.ScTec
							, @KgTeo	        = tps.KgTeo
							, @NumSMED	        = tps.NumSMED
							, @RawMat	        = ql.RawMat
							, @BatchQty	        = ql.BatchQty
							, @ItemDescr        = i.ItemDescr
							, @CodifProfilo     = i.Class01
							, @ClasseMerc       = i.Class02
							, @CodClientAssoc   = i.Class03

				FROM dbo.QuoteList ql 
				INNER JOIN dbo.TabProdSc tps ON ql.KeyAM = tps.KeyAM 
				INNER JOIN dbo.ItemDet i ON ql.CodItem = i.CodItem
				WHERE	ql.QuoteType	= @QuoteType
					AND	ql.CodQuote		= @CodQuote
					AND	ql.QuoteRev		= @QuoteRev
				ORDER BY tps.KgTeo DESC

				-- =================================================================================
				-- recupero dall'offerta il valore del PACKAGE/IMBALLO scelto e i dati relativi
				-- Secondo la logica Client-Item-Package ( vedi funzione )
				-- =================================================================================
				-- SET @CodPackag = ( SELECT dbo.f_getCodPackag( @CodItem , @CodClient ) )
				-- attenzione è una function tabellare
				--SELECT @CodPackag = CodPackag, @PTotQta = TotQta, @PWeight = Weight, @PTare = Tare,
				--       @NumImb = NumImb, @PDurata = Durata, @PLiv = LivPackag , @PLivDett = LivPackagDet
				--FROM f_getDataCodPackag ( @CodItem, @CodClient)

				EXEC dbo.stp_getDataCodPackag @CodItem, @CodClient, @CodPackag = @CodPackag OUT, @TotQta = @PTotQta OUT, @Weight = @PWeight OUT, @Tare = @PTare OUT,
					   @NumImb = @NumImb OUT, @Durata = @PDurata OUT, @LivPackag = @PLiv OUT, @LivPackagDet = @PLivDett OUT

			END
		-- --------------------------------------------------------------------------------------------
		-- se offerta tipo 'S' non recupero dati da storico ma li cerco da tabella apposita..
		-- --------------------------------------------------------------------------------------------
		ELSE IF (@QuoteType = 'S')
			BEGIN
				 -- salvo i parametri da QuoteSimPar a #Quoteparam
				INSERT INTO #Quoteparam(Quotetype, CodQuote, QuoteRev ,ProcessNum, Descr, Parameter) 
				SELECT  Quotetype, CodQuote, QuoteRev, '01' AS ProcessNum, NomePar AS Descr, ValPar AS Parameter
				FROM    dbo.QuoteSimPar
				WHERE   QuoteType	= @QuoteType
					AND	CodQuote	= @CodQuote
					AND	QuoteRev	= @QuoteRev
					AND NomePar NOT IN ('CodDiesGroup', 'CodPlant')

				-- recupero parametri da SIM iniziali......
				;WITH myCTE as 
				(   -- Pivot table 
					SELECT CodDiesGroup, CodPlant, CodPackag, NetProd01_sim, NetProd04_sim
					FROM
					(   SELECT NomePar, ValPar 
						FROM dbo.QuoteSimPar
						WHERE QuoteType = @QuoteType AND CodQuote = @CodQuote AND QuoteRev = @QuoteRev ) AS SourceTable
					PIVOT ( MIN(ValPar) FOR NomePar IN ( CodDiesGroup, CodPlant, CodPackag, NetProd01_sim, NetProd04_sim )
					) AS PivotTable
				)

				SELECT  @CodDiesGroup   = CodDiesGroup,
						@CodPlant       = CodPlant,
						@CodPackag      = ISNULL(CodPackag, 0),
						@ProdTeo_sim    = NetProd01_sim,			-- ??? @ProdTeo_sim NON USATA?
						@ProdTeoImb_sim = NetProd04_sim				-- ??? @ProdTeoImb_sim NON USATA ?
				FROM myCTE
				

                -- 2014.10.12 anticipato calcolo x avere holeNum x chiave AMIL successiva...
				SELECT	    @CodDiesGroup   = ISNULL(@CodDiesGroup, '')
				SELECT	    @CodPlant       = ISNULL(@CodPlant, '')
				SELECT	    @CodPlantCMIL   = ISNULL(@CodPlant, '0000')
				SELECT	    @HoleNum        = dbo.f_getSubstring(@CodDiesGroup, '-', 3)

                -- 2014.09.09 FIX calcolo prod teorica imballo da lookup...
				SELECT	TOP 1 @ProdTeo	        = tps.ProdTeo							
				FROM dbo.QuoteList ql 
                    -- modifica 2014.10.12 messa chiave AMIL
				    --INNER JOIN dbo.TabProdSc tps ON ql.KeyAM = tps.KeyAM 
				    INNER JOIN dbo.TabProdSc tps ON ql.KeyAM  + '-' + @CodPlantCMIL + '-' + CAST(ISNULL(@HoleNum,0) AS NVARCHAR(10)) = tps.KeyAMIL 
				    WHERE	ql.QuoteType	= @QuoteType
					    AND	ql.CodQuote		= @CodQuote
					    AND	ql.QuoteRev		= @QuoteRev
				    ORDER BY tps.KgTeo DESC

				SELECT	TOP 1 @CodItem	    = ql.CodItem
							, @KeyAM	    = ql.KeyAM
							, @KeyAMI	    = ql.KeyAM + '-' + @CodPlantCMIL
							, @KeyAMIL	    = ql.KeyAM + '-' + @CodPlantCMIL + '-' + CAST(ISNULL(@HoleNum,0) AS NVARCHAR(10))
							, @ScTec	    = 0
							, @KgTeo	    = 0
							, @NumSMED	    = 0
							, @RawMat	    = ql.RawMat
							, @BatchQty	    = ql.BatchQty
							, @ItemDescr    = i.ItemDescr
							, @CodifProfilo = i.Class01
							, @ClasseMerc   = i.Class02
							, @CodClientAssoc = i.Class03

				FROM dbo.QuoteList ql 
				INNER JOIN dbo.ItemDet i ON ql.CodItem = i.CodItem
				WHERE	ql.QuoteType	= @QuoteType
					AND	ql.CodQuote		= @CodQuote
					AND	ql.QuoteRev		= @QuoteRev

				-- provo a caricare dati produzione da KeyAMIL + CodDiesGroup
				SELECT TOP 1  @ScTec	    = ISNULL(ScTec, 0)
							, @KgTeo	    = ISNULL(KgTeo, 0)
							, @NumSMED	    = ISNULL(NumSMED, 0)
                            -- 2014.08.22 - TOLTO NON deve usare la teorica...
							--, @ProdTeo	    = ISNULL(ProdTeo, 0) -- VERIFICARE!!! NON DOVREBBE FARLO... ha già calcolato
				FROM        dbo.TabProdSc
				WHERE       KeyAMIL = @KeyAMIL
					AND     CodDiesGroup = @CodDiesGroup


				-- =================================================================================
				-- carico dati package generali
				-- =================================================================================

				SELECT @PTotQta = TotQta, @PWeight = Weight, @PTare = Tare, @NumImb = NumImb, @PDurata = Durata
						 , @PLiv = 'Package', @PLivDett= CodPackag
				FROM dbo.Package2 WHERE CodPackag = @CodPackag

				--SELECT @CodPackag = CodPackag, @PTotQta = TotQta, @PWeight = Weight, @PTare = Tare,
				--       @NumImb = NumImb, @PDurata = Durata, @PLiv = LivPackag , @PLivDett = LivPackagDet
				--FROM f_getDataCodPackag ( @CodItem, @CodClient)

			END

		-- e aggiorno il CodPackage in QuoteRM
		UPDATE	dbo.QuoteRM
			SET CodPackag = ISNULL(@CodPackag,'')
		FROM dbo.QuoteRM
		WHERE	QuoteType	= @QuoteType
			AND	CodQuote	= @CodQuote
			AND	QuoteRev	= @QuoteRev

		INSERT INTO #QuoteParam(QuoteType, CodQuote, QuoteRev, ProcessNum, Descr, Parameter)
		VALUES  ( @QuoteType, @CodQuote, @QuoteRev, '01', 'ItemDescr',      @ItemDescr )
			,   ( @QuoteType, @CodQuote, @QuoteRev, '01', 'CodifProfilo',   @CodifProfilo )
			,   ( @QuoteType, @CodQuote, @QuoteRev, '01', 'ClasseMerc',     @ClasseMerc ) 
			,   ( @QuoteType, @CodQuote, @QuoteRev, '01', 'CodClientAssoc', @CodClientAssoc )

		INSERT INTO #QuoteParam(QuoteType, CodQuote, QuoteRev, ProcessNum, Descr, Parameter)
		SELECT  @QuoteType, @CodQuote, @QuoteRev, '01', 'ClientNameAssoc', ClientDet.ClientName
		FROM dbo.ClientDet 
		WHERE ClientDet.CodClient = @CodClientAssoc
		
		-- INFORMAZIONI su MATRICE
		INSERT INTO #QuoteParam(QuoteType, CodQuote, QuoteRev, ProcessNum, Descr, Parameter)
		VALUES (@QuoteType, @CodQuote, @QuoteRev, '01', 'CodDiesGroup', ISNULL(@CodDiesGroup, '') )

		SET @strTemp = dbo.f_getSubstring(@CodDiesGroup, '-', 1) 
		INSERT INTO #QuoteParam(QuoteType, CodQuote, QuoteRev, ProcessNum, Descr, Parameter)
		VALUES (@QuoteType, @CodQuote, @QuoteRev, '01', 'TipoDies', ISNULL(@strTemp, '') ) 

		SET @strTemp = dbo.f_getSubstring(@CodDiesGroup, '-', 2)
		INSERT INTO #QuoteParam(QuoteType, CodQuote, QuoteRev, ProcessNum, Descr, Parameter)
		VALUES (@QuoteType, @CodQuote, @QuoteRev, '01', 'DiamDies', CASE WHEN ISNULL(@strTemp,'') = '' THEN 1 ELSE @strTemp END )
		
		SET @strTemp = dbo.f_getSubstring(@CodDiesGroup, '-', 3)
		INSERT INTO #QuoteParam(QuoteType, CodQuote, QuoteRev, ProcessNum, Descr, Parameter)
		VALUES (@QuoteType, @CodQuote, @QuoteRev, '01', 'HoleNumDies', ISNULL(@strTemp, 1) )

		INSERT INTO #QuoteParam(QuoteType, CodQuote, QuoteRev, ProcessNum, Descr, Parameter)
		SELECT	@QuoteType, @CodQuote, @QuoteRev, '01', 'NumDiesInList', COUNT(CodDies)
		FROM	dbo.DiesDet
		WHERE	CodDiesGroup = @CodDiesGroup AND CodItem = @CodItem

        ------------------------------------------------------------------------------------------------------------
        -- 2014.09.10 faccio MODIFICA x contare matrici esauste da articolo SE disponibili...
        --
        SELECT	@NumDiesExaust = COUNT(CodDies)
		FROM	dbo.DiesDet
		WHERE	CodDiesGroup = @CodDiesGroup AND CodItem = @CodItem AND Active = 0

        -- se zero ricalcolo x gruppo e salvo...
        IF(@NumDiesExaust = 0)
            BEGIN
                SELECT	@NumDiesExaust = COUNT(CodDies)
		        FROM	dbo.DiesDet
		        WHERE	CodDiesGroup = @CodDiesGroup AND Active = 0
            END

        INSERT INTO #QuoteParam(QuoteType, CodQuote, QuoteRev, ProcessNum, Descr, Parameter)
		VALUES  ( @QuoteType, @CodQuote, @QuoteRev, '01', 'NumDiesExaust'  , @NumDiesExaust)
		
		--INSERT INTO #QuoteParam(QuoteType, CodQuote, QuoteRev, ProcessNum, Descr, Parameter)
		--SELECT	@QuoteType, @CodQuote, @QuoteRev, '01', 'NumDiesExaust', COUNT(CodDies)
		--FROM	dbo.DiesDet
		--WHERE	CodDiesGroup = @CodDiesGroup AND Active = 0
        --
        -- FINE modifica 2014.09.10
        ------------------------------------------------------------------------------------------------------------

		
		-- fix valori null!!
		SET @CodPlant   = ISNULL(@CodPlant, '')
		SET @KeyAM      = ISNULL(@KeyAM, '')
		SET @KeyAMIL    = ISNULL(@KeyAMIL, '')
		SET @NumSMED    = ISNULL(@NumSMED, 0) 
		SET @BatchQty   = ISNULL(@BatchQty, 0) 
		SET @KgTeo      = ISNULL(@KgTeo, 0)
		SET @RawMat     = ISNULL(@RawMat, '')
		SET @ProdTeo    = ISNULL(@ProdTeo, 0) 
		SET @ProdTeoImb = ISNULL(@ProdTeoImb, 0) 
		SET @ScTec      = ISNULL(@ScTec, 0)
			
		-- inserisco parametri calcolati x lavorazione estrusione
		INSERT INTO #QuoteParam(QuoteType, CodQuote, QuoteRev, ProcessNum, Descr, Parameter)
		VALUES  ( @QuoteType, @CodQuote, @QuoteRev, '01', 'CodPlant'  , @CodPlant)
			   ,( @QuoteType, @CodQuote, @QuoteRev, '01', 'KeyAM'     , @KeyAM)
			   ,( @QuoteType, @CodQuote, @QuoteRev, '01', 'KeyAMIL'   , @KeyAMIL)
			   ,( @QuoteType, @CodQuote, @QuoteRev, '01', 'NumSMED'   , CONVERT(NVARCHAR(100) , @NumSMED))
			   ,( @QuoteType, @CodQuote, @QuoteRev, '01', 'KgTeo'     , CONVERT(NVARCHAR(100) , @KgTeo))

		-- -----------------------------------------
		---- inserisco lavorazione estrusione!
		-- -----------------------------------------
		-- *** verifica errori ***
		SELECT @errorScore  = @errorScore + CASE WHEN @ProdTeo = 0 THEN 1 ELSE 0 END,
			   @valid       =               CASE WHEN @ProdTeo = 0 THEN 0 ELSE @valid END

		INSERT INTO #QuoteWorkInt (QuoteType, CodQuote, QuoteRev, ProcessNum, CodPlant, Class01, Class02, Class03, NetProd, WSR, valid)
		SELECT	@QuoteType, @CodQuote, @QuoteRev, '01', @CodPlant, @KeyAM, @KeyAMIL, @RawMat, @ProdTeo, @ScTec, @valid

		INSERT INTO #QuoteParam (QuoteType, CodQuote, QuoteRev, ProcessNum, Descr, Parameter)
		SELECT	@QuoteType, @CodQuote, @QuoteRev, '01', 'KgProdotti', ISNULL(SUM(KgTeo),0)
		FROM	dbo.QuoteList ql 
		INNER JOIN dbo.TabProdSc tps ON ql.KeyAM = tps.KeyAM
		WHERE	ql.QuoteType	= @QuoteType
			AND	ql.CodQuote		= @CodQuote
			AND	ql.QuoteRev		= @QuoteRev
			
		-- inserisco dati mancanti di MSR/CSR (scarto cesoia x estrusione) - DSR è NULLO x estrusione!
		UPDATE	#QuoteWorkInt
		SET     MSR = rmd.CSR
		FROM	#QuoteWorkInt qwi
		INNER JOIN dbo.RawMatDet rmd ON qwi.Class03 = rmd.RawMat

        IF (@QuoteType IN ('Q', 'R', 'C' ) )    -- Quotation, Reddittivity, Cost List
			BEGIN
		        -- calcolo i costi legati alla fase estrusione!
		        UPDATE	#QuoteWorkInt
		        SET		FC4UG = CASE WHEN qwi.NetProd = 0 OR cp.QuotaManStd = 0 THEN -99 ELSE (cp.FC * cp.QuotaPlantStd / cp.QuotaManStd) / qwi.NetProd END
			          , VC4UG = CASE WHEN qwi.NetProd = 0 OR cp.QuotaManStd = 0 THEN -99 ELSE (cp.VC * cp.QuotaPlantStd / cp.QuotaManStd) / qwi.NetProd END
			          , OH4UG = CASE WHEN qwi.NetProd = 0 OR cp.QuotaManStd = 0 THEN -99 ELSE (cp.OH * cp.QuotaPlantStd / cp.QuotaManStd) / qwi.NetProd END
			          , SC4UG = CASE WHEN ql.BatchQty = 0                       THEN -99 ELSE cp.SC / ql.BatchQty END
			          , valid = CASE WHEN qwi.NetProd = 0 OR cp.QuotaManStd = 0 OR ql.BatchQty = 0 THEN 0 ELSE qwi.valid END   -- attenzione che è già impostato sopra
		        FROM	#QuoteWorkInt qwi
		        INNER JOIN dbo.Cost2Plant cp ON qwi.CodPlant = cp.CodPlant AND qwi.ProcessNum = cp.ProcessNum
		        INNER JOIN dbo.QuoteList ql ON qwi.QuoteType = ql.QuoteType AND qwi.CodQuote = ql.CodQuote AND qwi.QuoteRev = ql.QuoteRev
		        WHERE	qwi.ProcessNum = '01'
		    END

        -- 2014.10.12 modifica x gestione del caso SIM come produttività da impiegare x calcoli
        ELSE IF (@QuoteType = 'S' ) 
            BEGIN
            
                -- calcolo i costi legati alla fase estrusione!
		        UPDATE	#QuoteWorkInt
		        SET		FC4UG = CASE WHEN @NetProd01_sim = 0 OR cp.QuotaManStd = 0 THEN -99 ELSE (cp.FC * cp.QuotaPlantStd / cp.QuotaManStd) / @NetProd01_sim END
			          , VC4UG = CASE WHEN @NetProd01_sim = 0 OR cp.QuotaManStd = 0 THEN -99 ELSE (cp.VC * cp.QuotaPlantStd / cp.QuotaManStd) / @NetProd01_sim END
			          , OH4UG = CASE WHEN @NetProd01_sim = 0 OR cp.QuotaManStd = 0 THEN -99 ELSE (cp.OH * cp.QuotaPlantStd / cp.QuotaManStd) / @NetProd01_sim END
			          , SC4UG = CASE WHEN ql.BatchQty = 0                          THEN -99 ELSE cp.SC / ql.BatchQty END
			          , valid = CASE WHEN @NetProd01_sim = 0 OR cp.QuotaManStd = 0 OR ql.BatchQty = 0 THEN 0 ELSE qwi.valid END   -- attenzione che è già impostato sopra
		        FROM	#QuoteWorkInt qwi
		        INNER JOIN dbo.Cost2Plant cp ON qwi.CodPlant = cp.CodPlant AND qwi.ProcessNum = cp.ProcessNum
		        INNER JOIN dbo.QuoteList ql ON qwi.QuoteType = ql.QuoteType AND qwi.CodQuote = ql.CodQuote AND qwi.QuoteRev = ql.QuoteRev
		        WHERE	qwi.ProcessNum = '01'
            END

		-- *** verifica errori ***
		SELECT @errorScore  = @errorScore + CASE WHEN valid = 0 THEN 1 ELSE 0 END,
			   @valid       =               CASE WHEN valid = 0 THEN 0 ELSE @valid END
		FROM #QuoteWorkInt qwi
		--INNER JOIN dbo.Cost2Plant cp ON qwi.CodPlant = cp.CodPlant AND qwi.ProcessNum = cp.ProcessNum
		--INNER JOIN dbo.QuoteList ql ON qwi.QuoteType = ql.QuoteType AND qwi.CodQuote = ql.CodQuote AND qwi.QuoteRev = ql.QuoteRev
		WHERE	qwi.ProcessNum = '01'

		 -- inserisco lavorazione incestatura!
		INSERT INTO #QuoteWorkInt (QuoteType, CodQuote, QuoteRev, ProcessNum, CodPlant, Class01, Class02, Class03)
		SELECT	@QuoteType, @CodQuote, @QuoteRev, '02', @CodPlant, @KeyAM, @KeyAMI, @RawMat
		
		-- inserisco dati mancanti di DSR x incestatura come 1 - OUT/IN
		UPDATE	#QuoteWorkInt
		SET		DSR   = CASE td.TotIN WHEN 0 THEN -99 ELSE 1 - CAST(td.TotOUT AS DECIMAL(18,6)) / CAST(td.TotIN AS DECIMAL(18,6)) END , 
				valid = CASE td.TotIN WHEN 0 THEN 0 ELSE 1 END
		FROM	#QuoteWorkInt qwi
		INNER JOIN dbo.TabDifett td ON qwi.Class02 = td.KeyAMI AND qwi.ProcessNum = td.ProcessNum
		WHERE	qwi.ProcessNum = '02' -- solo incestatura

		-- *** verifica errori ***
		SELECT @errorScore  = @errorScore + CASE WHEN qwi.valid = 0 THEN 1 ELSE 0 END,
			   @valid       =               CASE WHEN qwi.valid = 0 THEN 0 ELSE @valid END
		FROM	#QuoteWorkInt qwi
--        INNER JOIN dbo.TabDifett td ON qwi.Class02 = td.KeyAMI AND qwi.ProcessNum = td.ProcessNum
		WHERE	qwi.ProcessNum = '02' -- solo incestatura
		
		-- inserisco lavorazione FORNO!
		INSERT INTO #QuoteWorkInt(QuoteType, CodQuote, QuoteRev, ProcessNum, CodPlant, Class01, Class02, Class03)
		SELECT	@QuoteType, @CodQuote, @QuoteRev, '03', @CodPlant, @KeyAM, @KeyAMI, @RawMat
		
		-- inserisco lavorazione imballo!
		INSERT INTO #QuoteWorkInt(QuoteType, CodQuote, QuoteRev, ProcessNum, CodPlant, Class01, Class02, Class03, Class04, Class05)
		SELECT	@QuoteType, @CodQuote, @QuoteRev, '04', @CodPlant, @KeyAM, @KeyAMIL, @RawMat, @CodItem, @KeyAMI

        -- 2014.08.22 inserito passaggio di calcolo produttività simulata imballo a seconda caso 'S' o caso standard...
        DECLARE @valid04 BIT = 0
        IF (@QuoteType <> 'S')
            BEGIN
                SELECT  @ProdTeoImb = CASE @PDurata WHEN 0 THEN 0 ELSE @PTotQta / @PDurata END,
                        @valid04    = CASE WHEN @PDurata = 0 OR @PTotQta = 0 THEN 0 ELSE 1 END       -- @PTotQta non può essere mai = 0
            END
        ELSE
            BEGIN
                SELECT  @ProdTeoImb = CASE @PDurata WHEN 0 THEN 0 ELSE @PTotQta / @PDurata END,
                        @valid04    = 1 
            END

		UPDATE	qwi
			SET		NetProd = @ProdTeoImb,
					valid   = @valid04
		FROM	#QuoteWorkInt AS qwi
--		INNER JOIN dbo.TabImbArt ti ON qwi.Class04 = ti.KeyA
		WHERE	qwi.ProcessNum = '04' -- solo imballo

		-- *** controllo errori
		SELECT @errorScore  = @errorScore + CASE WHEN @PDurata = 0 OR @PTotQta = 0 OR @PWeight = 0 THEN 1 ELSE 0 END,           -- verificare @PWeight -> dove salvo l'errore?
			   @valid       =               CASE WHEN @PDurata = 0 OR @PTotQta = 0 OR @PWeight = 0 THEN 0 ELSE @valid END

		-- parametro num imballatori
		INSERT INTO #QuoteParam(QuoteType, CodQuote, QuoteRev, ProcessNum, Descr, Parameter)
		SELECT	@QuoteType, @CodQuote, @QuoteRev, '04', 'QuotaMan', @NumImb
		
		-- parametro Livello search package/imballo
		INSERT INTO #QuoteParam(QuoteType, CodQuote, QuoteRev, ProcessNum, Descr, Parameter)
		SELECT	@QuoteType, @CodQuote, @QuoteRev, '04', 'LivPackage', @PLiv

		-- parametro Livello search package/imballo
		INSERT INTO #QuoteParam(QuoteType, CodQuote, QuoteRev, ProcessNum, Descr, Parameter)
		SELECT	@QuoteType, @CodQuote, @QuoteRev, '04', 'LivPackageDett', @PLivDett

		-- calcolo i costi legati alla fase di imballo!
        IF (@QuoteType IN ('Q', 'R', 'C' ) )    -- Quotation, Reddittivity, Cost List
			BEGIN
		        UPDATE	#QuoteWorkInt
		        SET		FC4UG = CASE WHEN qwi.NetProd = 0 OR cp.QuotaManStd = 0 THEN -99 ELSE ( ( cp.FC * cp.QuotaPlantStd ) * ( @NumImb / cp.QuotaManStd ) ) / qwi.NetProd END
			          , VC4UG = CASE WHEN qwi.NetProd = 0 OR cp.QuotaManStd = 0 THEN -99 ELSE ( ( cp.VC * cp.QuotaPlantStd ) * ( @NumImb / cp.QuotaManStd ) ) / qwi.NetProd END
			          , OH4UG = CASE WHEN qwi.NetProd = 0 OR cp.QuotaManStd = 0 THEN -99 ELSE ( ( cp.OH * cp.QuotaPlantStd ) * ( @NumImb / cp.QuotaManStd ) ) / qwi.NetProd END
			          , SC4UG = CASE WHEN ql.BatchQty = 0                       THEN -99 ELSE cp.SC / ql.BatchQty END
			          , valid = CASE WHEN qwi.NetProd = 0 OR cp.QuotaManStd = 0 OR ql.BatchQty = 0 THEN 0 ELSE 1 END
		        FROM	#QuoteWorkInt qwi
		        INNER JOIN dbo.Cost2Plant cp ON qwi.CodPlant = cp.CodPlant AND qwi.ProcessNum = cp.ProcessNum
		        INNER JOIN dbo.QuoteList ql ON qwi.QuoteType = ql.QuoteType AND qwi.CodQuote = ql.CodQuote AND qwi.QuoteRev = ql.QuoteRev
		        WHERE	qwi.ProcessNum = '04' -- solo imballo
            END
        ELSE IF (@QuoteType = 'S') 
            BEGIN
		        UPDATE	#QuoteWorkInt
		        SET		FC4UG = CASE WHEN @NetProd04_sim = 0 OR cp.QuotaManStd = 0 THEN -99 ELSE ( ( cp.FC * cp.QuotaPlantStd ) * ( @NumImb / cp.QuotaManStd ) ) / @NetProd04_sim END
			          , VC4UG = CASE WHEN @NetProd04_sim = 0 OR cp.QuotaManStd = 0 THEN -99 ELSE ( ( cp.VC * cp.QuotaPlantStd ) * ( @NumImb / cp.QuotaManStd ) ) / @NetProd04_sim END
			          , OH4UG = CASE WHEN @NetProd04_sim = 0 OR cp.QuotaManStd = 0 THEN -99 ELSE ( ( cp.OH * cp.QuotaPlantStd ) * ( @NumImb / cp.QuotaManStd ) ) / @NetProd04_sim END
			          , SC4UG = CASE WHEN ql.BatchQty = 0                          THEN -99 ELSE cp.SC / ql.BatchQty END
			          , valid = CASE WHEN @NetProd04_sim = 0 OR cp.QuotaManStd = 0 OR ql.BatchQty = 0 THEN 0 ELSE 1 END
		        FROM	#QuoteWorkInt qwi
		        INNER JOIN dbo.Cost2Plant cp ON qwi.CodPlant = cp.CodPlant AND qwi.ProcessNum = cp.ProcessNum
		        INNER JOIN dbo.QuoteList ql ON qwi.QuoteType = ql.QuoteType AND qwi.CodQuote = ql.CodQuote AND qwi.QuoteRev = ql.QuoteRev
		        WHERE	qwi.ProcessNum = '04' -- solo imballo
            END

		-- *** verifica errori ***
		SELECT @errorScore  = @errorScore + CASE WHEN qwi.valid = 0 THEN 1 ELSE 0 END,
			   @valid       =               CASE WHEN qwi.valid = 0 THEN 0 ELSE @valid END
		FROM	#QuoteWorkInt qwi
		--INNER JOIN dbo.Cost2Plant cp ON qwi.CodPlant = cp.CodPlant AND qwi.ProcessNum = cp.ProcessNum
		--INNER JOIN dbo.QuoteList ql ON qwi.QuoteType = ql.QuoteType AND qwi.CodQuote = ql.CodQuote AND qwi.QuoteRev = ql.QuoteRev
		WHERE	qwi.ProcessNum = '04' -- solo imballo

		-- inserisco dati mancanti di DSR x imballo come 1 - OUT/IN
		UPDATE	#QuoteWorkInt
		SET		DSR = 1 - ( CASE WHEN CAST(td.TotIN AS DECIMAL(18,6)) = 0 THEN 1 ELSE CAST(td.TotOUT AS DECIMAL(18,6)) / CAST(td.TotIN AS DECIMAL(18,6)) END ) ,
				valid = CASE WHEN td.TotIN = 0 THEN 0 ELSE 1 END
		FROM	#QuoteWorkInt qwi
		INNER JOIN dbo.TabDifett td ON qwi.Class05 = td.KeyAMI AND qwi.ProcessNum = td.ProcessNum 
		WHERE	qwi.ProcessNum = '04' -- solo imballo

		-- *** verifica errori ***
		SELECT @errorScore  = @errorScore + CASE WHEN qwi.valid = 0 THEN 1 ELSE 0 END,
			   @valid       =               CASE WHEN qwi.valid = 0 THEN 0 ELSE @valid END
		FROM	#QuoteWorkInt qwi
		--INNER JOIN dbo.TabDifett td ON qwi.Class05 = td.KeyAMI AND qwi.ProcessNum = td.ProcessNum 
		WHERE	qwi.ProcessNum = '04' -- solo imballo
		
		-- recupero le MAC fase 01
		SELECT	 @MAC_SC	= MCR
				,@MAC_ST	= WCR
		FROM	#QuoteWorkInt
		WHERE	ProcessNum  = '01'

		-- recupero le MAC fase 02
		SELECT	@MAC_IN	    = DCR
		FROM	#QuoteWorkInt
		WHERE   ProcessNum  = '02'

		-- recupero le MAC fase 04
		SELECT	@MAC_IM		= DCR
		FROM	#QuoteWorkInt
		WHERE	ProcessNum  = '04'

		-- calcolo percentuale vendita rottame
		SELECT	@SSR = SSR
		FROM	dbo.RawMatDet
		WHERE	RawMat = @RawMat
				

		-- NOTA :   la transazione posso probabilmente iniziarla qui visto che è il 
		--          primo Update/insert/delete su tabelle non temporanee delete a parte
		 IF (@QuoteType = 'S')
			BEGIN
				-- recupero i 3 scarti...
				DECLARE @WSR01_sim  DECIMAL(18,6) = 0
				DECLARE @MSR01_sim  DECIMAL(18,6) = 0
				DECLARE @DSR_sim    DECIMAL(18,6) = 0

				 -- recupero parametri da SIM iniziali......
				;WITH myCTE2 as
				(
					-- Pivot table 
					SELECT WSR01_sim, MSR01_sim, DSR_sim
					FROM
					(SELECT NomePar, ValPar 
						FROM dbo.QuoteSimPar
						WHERE QuoteType = @QuoteType
						AND CodQuote    = @CodQuote
						AND QuoteRev    = @QuoteRev
						) AS SourceTable
					PIVOT
					( MIN(ValPar) 
						FOR NomePar IN
						(
							WSR01_sim, MSR01_sim, DSR_sim
						)
					) AS PivotTable
				)

				SELECT  @MAC_ST_sim     = 1 / (1 - CONVERT(DECIMAL(18,6), WSR01_sim)),
						@MAC_SC_sim     = 1 / (1 - CONVERT(DECIMAL(18,6), MSR01_sim)),
						@MAC_IN_sim     = 1,
						@MAC_IM_sim     = 1 / (1 - CONVERT(DECIMAL(18,6), DSR_sim))
				FROM    myCTE2

				-- salvo la messa a cento da simulazione in variabile
				SET     @FCR_sim = CASE WHEN ( @MAC_ST_sim * @MAC_SC_sim * @MAC_IN_sim * @MAC_IM_sim ) = 0 
										THEN 1 
										ELSE ( @MAC_ST_sim * @MAC_SC_sim * @MAC_IN_sim * @MAC_IM_sim ) 
								   END

				-- salvo in tabella!
				UPDATE	dbo.QuoteRM
				SET		FCR = ISNULL(@FCR_sim,1)
				WHERE	QuoteType	= @QuoteType
					AND	CodQuote	= @CodQuote
					AND	QuoteRev	= @QuoteRev
					AND	RawMat		= @RawMat
			END
		 ELSE
			BEGIN    
				-- update rese RawMat!
				UPDATE	dbo.QuoteRM
				SET		FCR = @MAC_SC * @MAC_ST * @MAC_IN * @MAC_IM
				WHERE	QuoteType	= @QuoteType
					AND	CodQuote	= @CodQuote
					AND	QuoteRev	= @QuoteRev
					AND	RawMat		= @RawMat
			END
		-- inserisco i costi delle utilities in QuoteOC
			
		-- inserisco altri costi x lavorazione estrusione! GAS ed EE
		INSERT INTO #QuoteOC(QuoteType, CodQuote, QuoteRev, ProcessNum, CodPlant, Class01, Class02, TotQty, TotCost, Quota)
		SELECT	@QuoteType, @CodQuote, @QuoteRev, '01', @CodPlant, CodUtil, @RawMat, @BatchQty, ISNULL(UnitCost * @BatchQty, 0), 1
		FROM	dbo.Utilities
		WHERE	CodPlant = @CodPlant

		-- *** controllo errori - se non trovo costi GAS ed EE segnalo errore
		IF @@ROWCOUNT = 0
		   SET @validStep = 0;
		ELSE       
		   SET @validStep = 1;

		SELECT @errorScore  = @errorScore + CASE WHEN @validStep = 0 THEN 1 ELSE 0 END,
			   @valid       =               CASE WHEN @validStep = 0 THEN 0 ELSE @valid END
		
		/*************************************************************
		* MATRICE
		*
		* calcolo prezzo e durata matrice con procedura a 5 step...
		* A) media ponderata prezzo ed ExpLife da DiesDet selezionando x CodItem + CodDiesGroup 
		* B) EOLLife x media ponderata su DiesDet dove Active = 0 e vita cmq superiore 5000 KG ( escludendo rotture accidentali )
		* C) SE prezzo = 0 --> prendo prezzo da DiesGroupDet selezionando x CodDiesGroup
		* D) Se EOL = 0 --> prendo ExpLife della singola matrice, se è 0 --> prendo EOLLife da DiesGroupDet selezionando x CodDiesGroup
		* E) Calcolo Price / Life
		*
		*************************************************************/

		-- se sono in simulazione leggo tutto direttamente da tab dbo.DiesGroupDet
		IF (@QuoteType = 'S')
			BEGIN
				SELECT	@DiesPrice      = Price,
						@DiesExpLife    = ExpLife, 
						@DiesEOLife     = CASE WHEN EOLLife > 0 THEN EOLLife ELSE ExpLife END, 
						@DiesByClass    = 1 -- imposto come calcolata matrice da gruppo
				FROM	dbo.DiesGroupDet
				WHERE	CodDiesGroup	= @CodDiesGroup
			END

		ELSE
			BEGIN

				-- (A) da DiesDet
				SELECT	@DiesPrice		= CASE WHEN SUM(ISNULL(ActLife, 1)) <> 0 THEN SUM(ISNULL(Price, 0)   * ISNULL(ActLife, 1)) / SUM(ISNULL(ActLife, 1)) END, 
						@DiesExpLife	= CASE WHEN SUM(ISNULL(ActLife, 1)) <> 0 THEN SUM(ISNULL(ExpLife, 0) * ISNULL(ActLife, 1)) / SUM(ISNULL(ActLife, 1)) END
				FROM	dbo.DiesDet
				WHERE	CodItem			= @CodItem 
					AND	CodDiesGroup	= @CodDiesGroup
				GROUP BY CodItem, CodDiesGroup

				-- (B) da DiesDet
				SELECT	@DiesEOLife		= AVG( ISNULL(ActLife, 0))
				FROM	dbo.DiesDet
				WHERE	CodItem			= @CodItem 
					AND	CodDiesGroup	= @CodDiesGroup
					AND	Active			= 0          -- solo matrici rottamate
					AND ActLife         > 5000       -- solo se hanno Life > 5000 Kg ( non rotture accidentali )
				GROUP BY CodItem, CodDiesGroup        
			END

		-- continuo!
		SET	@DiesPrice		= ISNULL(@DiesPrice,0)
		SET	@DiesExpLife	= ISNULL(@DiesExpLife,0)
		SET	@DiesEOLife		= ISNULL(@DiesEOLife,0)
		SET @validStep      = 1

		-- (C) verifico se prezzo è OK...
		IF (@DiesPrice = 0)
		BEGIN
			-- calcolo da DiesGroupDet
			SELECT	@DiesPrice		= ISNULL(Price, 0), @DiesByClass = 1 -- imposto come calcolata matrice da gruppo
			FROM	dbo.DiesGroupDet
			WHERE	CodDiesGroup	= @CodDiesGroup
		END
		
		-- (D) verifico se vita è OK...
		IF (@DiesEOLife = 0)
		BEGIN
			-- uso exp life articolo...
			SET	@DiesEOLife = @DiesExpLife
		END

		-- controllo che non sia nulla/vuota la durata...
		IF (@DiesEOLife = 0)
		BEGIN
			SELECT	@DiesEOLife = CASE WHEN EOLLife > 0 THEN EOLLife ELSE ExpLife END, 
					@DiesByClass = 1                                -- imposto come calcolata matrice da gruppo
			FROM	dbo.DiesGroupDet
			WHERE	CodDiesGroup	= @CodDiesGroup
		END
		
		-- controllo che non sia nulla/vuota la durata...
		IF ( @DiesEOLife > 0 AND @DiesPrice > 0 )
		  BEGIN 
			-- (E) Calcolo price/life!
			SET	@DiesPriceLife = @DiesPrice / @DiesEOLife
		  END
		ELSE 
		  BEGIN
			SET @DiesPriceLife = 0              -- metto a zero il DiesPriceLife
			SET @validStep     = 0              -- indico che valore non è valido  ( ND excel )
		  END
		
		 -- se è una simulazione uso cmq i valori caricati e non calcolati
		 IF (@QuoteType = 'S')
			BEGIN
				-- recupero i costi matrice da simulazione
				DECLARE @DiesPrice_sim DECIMAL(9,3) = 0
				DECLARE @DiesCommLife  DECIMAL(9,2) = 0 -- questa mi serve dopo?
				DECLARE @DiesTecLife   DECIMAL(9,2) = 0

				;WITH myCTE2 as
				(   -- Pivot table 
					SELECT DiesPrice_sim, DiesCommLife, DiesTecLife
					FROM
					(   SELECT NomePar, ValPar 
						FROM dbo.QuoteSimPar
						WHERE QuoteType = @QuoteType AND CodQuote = @CodQuote AND QuoteRev = @QuoteRev
					) AS SourceTable
					PIVOT ( MIN(ValPar) FOR NomePar IN ( DiesPrice_sim, DiesCommLife, DiesTecLife )
					) AS PivotTable
				)
				SELECT  @DiesPrice_sim  = DiesPrice_sim,
						@DiesCommLife   = DiesCommLife,
						@DiesTecLife    = DiesTecLife
				FROM    myCTE2              
				
				IF ( ISNULL(@DiesPrice_sim,0) = 0 OR ISNULL(@DiesTecLife,0) = 0 )
				BEGIN
				   SET @DiesPriceLife = 0
				   SET @validStep     = 0
				END
				ELSE 
				BEGIN
					SET @DiesPriceLife = @DiesPrice_sim / @DiesTecLife
					SET @validStep = 1   -- potrebbe essere stato messo = 0 da Quote non di simulazione
				END
		   END

		-- inserisco costi per Matrice: costo e durata da matrice, se non ci sono da gruppo, (anche solo uno dei due, ovviamente più facile trovare durata x matrice...)
		INSERT INTO #QuoteOC(QuoteType, CodQuote, QuoteRev, ProcessNum, CodPlant, Class01, Class02, TotQty, TotCost, Quota, valid)
		SELECT	@QuoteType, @CodQuote, @QuoteRev, '01', @CodPlant, 'MATRICE', @RawMat, @BatchQty, ISNULL(@DiesPriceLife * @BatchQty, 0), 1, @validStep

		-- *** controllo errori
		SELECT @errorScore  = @errorScore + CASE WHEN @validStep = 0 THEN 1 ELSE 0 END,
			   @valid       =               CASE WHEN @validStep = 0 THEN 0 ELSE @valid END

		-- inserisco parametri calcolati x matrice
		INSERT INTO #QuoteParam(QuoteType, CodQuote, QuoteRev, ProcessNum, Descr, Parameter)
		VALUES	( @QuoteType, @CodQuote, @QuoteRev, '01', 'DiesPrice',   CONVERT(NVARCHAR(100), @DiesPrice) )
			   ,( @QuoteType, @CodQuote, @QuoteRev, '01', 'DiesExpLife', CONVERT(NVARCHAR(100), @DiesExpLife) )
			   ,( @QuoteType, @CodQuote, @QuoteRev, '01', 'DiesEOLife',  CONVERT(NVARCHAR(100), @DiesEOLife) )
			   ,( @QuoteType, @CodQuote, @QuoteRev, '01', 'DiesByClass', CONVERT(NVARCHAR(100), ISNULL(@DiesByClass,0)) )

		/*************************************************************
		* VENDITA ROTTAME
		*
		* calcolo COSTO DI VENDITA PER LE 2 FASI ESTRUSIONE 01 ED IMBALLO 04
		* - calcolo costi variabili fase 01 / 04
		* - calcolo costo di vendita x fase 01 / 04
		*************************************************************/

		SELECT	@OCF01 = SUM(ISNULL(C4UG,0))
		FROM	#QuoteOC
			
		SELECT	@VCF01 = @OCF01 + VC4UG	
		FROM	#QuoteWorkInt
		WHERE	ProcessNum	= '01'
			
		SELECT	@VCF04 = @OCF01 + SUM(VC4UG)
		FROM	#QuoteWorkInt
			
		SELECT	@SellCostF01 =  CASE WHEN @QuoteType = 'S' THEN ((@MAC_ST_sim * @MAC_SC_sim * @MAC_IN_sim) - 1) ELSE ((@MAC_ST * @MAC_SC * @MAC_IN) - 1) END
									* (q.RawMatCost  + q.RawMatExtraCost - CASE WHEN SSVA > 0 THEN SSVA ELSE q.RawMatCost * SSVR END + @VCF01) 
									-- ((prodotto delle MAC = inverso del prodotto delle rese) - 1) * (costo Al - prezzo rivendita + costi var fase 01)
			  , @RefCostF01  = -- ( (A - B) / 100 - C )
							   (
								-- (A) = (costo pieno di acquisto + costi fase 1) * MAC * 100 (IN CENTESIMI)
								((q.RawMatCost + q.RawMatExtraCost + @VCF01) * 
								CASE WHEN @QuoteType = 'S' THEN (@MAC_ST_sim * @MAC_SC_sim * @MAC_IN_sim * 100) ELSE  (@MAC_ST * @MAC_SC * @MAC_IN * 100) END
								)
					 -- (B) = ((MAC * 100) - 100) * Resa di fonderia * (costo pieno acquisto - costo di trasformazione))
							  -	CASE WHEN @QuoteType = 'S' THEN ((@MAC_ST_sim * @MAC_SC_sim * @MAC_IN_sim * 100) - 100) ELSE ((@MAC_ST * @MAC_SC * @MAC_IN * 100) - 100) END
									* rmd.ProcYield * (q.RawMatCost + q.RawMatExtraCost + @VCF01 - rmd.ProcCost)
							   ) / 100 -- divido per 100 finale
								-- (C) = sottraggo costo pieno alluminio
							  - (q.RawMatCost + q.RawMatExtraCost + @VCF01)
		FROM	dbo.RawMatDet rmd 
		INNER JOIN dbo.QuoteRM q ON q.RawMat = rmd.RawMat
		WHERE	q.QuoteType	= @QuoteType
			AND	q.CodQuote	= @CodQuote
			AND	q.QuoteRev	= @QuoteRev
			AND	q.RawMat	= @RawMat
			
		SELECT	@SellCostF04 = CASE WHEN @QuoteType = 'S' THEN ((@MAC_IM_sim) - 1) ELSE ((@MAC_IM) - 1) END 
									* (q.RawMatCost  + q.RawMatExtraCost - CASE WHEN SSVA > 0 THEN SSVA ELSE q.RawMatCost * SSVR END + @VCF01 + @VCF04) 
									-- ((prodotto delle MAC = inverso del prodotto delle rese) - 1) * (costo Al - prezzo rivendita + costi var fase 01 e fase 04)
			  , @RefCostF04  = -- ( (A - B) / 100 - C )
							   (
								-- (A) = (costo pieno di acquisto + costi variabili fase 1 e 4) * MAC * 100 (IN CENTESIMI)
								((q.RawMatCost + q.RawMatExtraCost + @VCF01 + @VCF04) * 
								CASE WHEN @QuoteType = 'S' THEN (@MAC_IM_sim * 100) ELSE (@MAC_IM * 100) END
								)
								-- (B) = ((MAC * 100) - 100) * Resa di fonderia * (costo pieno acquisto - costo di trasformazione))
							  -	CASE WHEN @QuoteType = 'S' THEN ((@MAC_IM_sim * 100) - 100) ELSE ((@MAC_IM * 100) - 100) END 
									* rmd.ProcYield * (q.RawMatCost + q.RawMatExtraCost + @VCF01 + @VCF04 - rmd.ProcCost)
							   ) / 100 -- divido per 100 finale
								-- (C) = sottraggo costo pieno alluminio
							  - (q.RawMatCost + q.RawMatExtraCost + @VCF01 + @VCF04)

							  -- NOTA: usiamo (q.RawMatCost + q.RawMatExtraCost + @VCF01) e non (q.RawMatCost + q.RawMatExtraCost + @VCF01 + @RefCostF01) perché la differenza è minimale, si tratta di 10/20 PPM...

		FROM	dbo.RawMatDet rmd 
		INNER JOIN dbo.QuoteRM q ON q.RawMat = rmd.RawMat
		WHERE	q.QuoteType	= @QuoteType
			AND	q.CodQuote	= @CodQuote
			AND	q.QuoteRev	= @QuoteRev
			AND	q.RawMat	= @RawMat
		
		-- inserisco costi per VENDITA
		INSERT INTO #QuoteOC(QuoteType, CodQuote, QuoteRev, ProcessNum, CodPlant, Class01, Class02, TotQty, TotCost, Quota)
		VALUES ( @QuoteType, @CodQuote, @QuoteRev, '01', @CodPlant, 'VENDITA', @RawMat, @BatchQty, ISNULL(@SellCostF01 * @BatchQty, 0), @SSR )
		-- inserisco costi per ROTTAME
			  ,( @QuoteType, @CodQuote, @QuoteRev, '01', @CodPlant, 'ROTTAME', @RawMat, @BatchQty, ISNULL(@RefCostF01 * @BatchQty, 0), 1 - @SSR )
		-- inserisco costi per VENDITA
			  ,( @QuoteType, @CodQuote, @QuoteRev, '04', @CodPlant, 'VENDITA', @RawMat, @BatchQty, ISNULL(@SellCostF04 * @BatchQty, 0), @SSR )
		-- inserisco costi per ROTTAME
			  ,( @QuoteType, @CodQuote, @QuoteRev, '04', @CodPlant, 'ROTTAME', @RawMat, @BatchQty, ISNULL(@RefCostF04 * @BatchQty, 0), 1 - @SSR )
	
		-- calcolo Package Cost e RMWeight da tab PackageDet
		-- EXEC stp_packageCost @CodItem, @CodClient, @CodPackag, @PDesc=@PkgDesc OUTPUT, @RMWeight=@PRMWeight OUTPUT, @Weight=@PWeight OUTPUT, @Tare=@PTare OUTPUT, @PackCost=@PCost OUTPUT, @TareStRat=@PTareStRatio OUTPUT
		-- stored sostituita perchè la maggior parte dei calcoli li ho già fatti
		SELECT	@PCost          = CASE @PWeight WHEN 0 THEN 0 ELSE RMCost / @PWeight END
			  , @PRMWeight      = RMWeight
			  , @PkgDesc        = PackagDesc
			  , @PTareStRatio   = CASE @PWeight WHEN 0 THEN 0 ELSE ( RMWeight - @PTare) / @PWeight END
		FROM	dbo.PackagDet
		WHERE	CodPackag = @CodPackag

		-- inserisco costi per IMBALLO
		INSERT INTO #QuoteOC(QuoteType, CodQuote, QuoteRev, ProcessNum, CodPlant, Class01,  Class02, TotQty, TotCost, Quota, valid)
		SELECT	@QuoteType, @CodQuote, @QuoteRev, '04', @CodPlant, 'IMBALLO', @RawMat, @BatchQty, ISNULL(@PCost * @BatchQty, 0), 1, CASE WHEN ISNULL(@PCost * @BatchQty, 0) = 0 THEN 0 ELSE 1 END
				
		-- *** controllo errori - costo imballo non può essere = 0
		SELECT @errorScore  = @errorScore + CASE WHEN ISNULL(@PCost * @BatchQty, 0) = 0 THEN 1 ELSE 0 END,
			   @valid       =               CASE WHEN ISNULL(@PCost * @BatchQty, 0) = 0 THEN 0 ELSE @valid END

		-- inserisco parametri calcolati x imballaggio
		INSERT INTO #QuoteParam(QuoteType, CodQuote, QuoteRev, ProcessNum, Descr, Parameter)
		VALUES   ( @QuoteType, @CodQuote, @QuoteRev, '04', 'PkgDesc',                            @PkgDesc )
				,( @QuoteType, @CodQuote, @QuoteRev, '04', 'PRMWeight',   CONVERT(NVARCHAR(100), @PRMWeight ) )
				,( @QuoteType, @CodQuote, @QuoteRev, '04', 'PWeight',     CONVERT(NVARCHAR(100), @PWeight ) ) 
				,( @QuoteType, @CodQuote, @QuoteRev, '04', 'PTare',       CONVERT(NVARCHAR(100), @PTare) )
				,( @QuoteType, @CodQuote, @QuoteRev, '04', 'TareStRatio', CONVERT(NVARCHAR(100), @PTareStRatio ) )
		
		
		---------------------------------------------	
		-- inserisco costi per TRASPORTI
		---------------------------------------------
		-- recupero tipo di trasporto ( se ha costi o meno )
		SELECT	@HasTC = i.HasTC
		FROM	dbo.QuoteList q 
		INNER JOIN dbo.Incoterms i ON q.CodInco = i.CodInco
		WHERE	q.QuoteType	= @QuoteType
			AND	q.CodQuote	= @CodQuote
			AND	q.QuoteRev	= @QuoteRev

		-- Se non trovo @HasTC setto i valori in modo che diano errore
		IF @HasTC IS NULL
			BEGIN 
			   SET @HasTC      =  1
			   SET @TranspCost =  0
			END
		ELSE
			BEGIN 
				-- recupero zona da cliente...
				SELECT	@TranspZone = TranspZone
				FROM	dbo.ClientDet	
				WHERE	CodClient	= @CodClient

				-- recupero costi trasporto 
				SELECT	@TranspCost = TranspCost     -- se non lo trova rimane a 0
				FROM	dbo.TranspCostDet
				WHERE	TranspZone	= @TranspZone
			END

		INSERT INTO #QuoteOC(QuoteType, CodQuote, QuoteRev, ProcessNum, CodPlant, Class01,  Class02, TotQty, TotCost, Quota, valid)
		SELECT	@QuoteType, @CodQuote, @QuoteRev, '04', @CodPlant, 'TRASPORTI', @RawMat, @BatchQty, ISNULL(@HasTC * @TranspCost * @BatchQty, 0), 1
			  , CASE WHEN @HasTC = 1 AND @TranspCost = 0 THEN 0 ELSE 1 END 

		-- *** controllo errori - se previsti costi imballo allora devo avere il costo <> 0
		SELECT @errorScore  = @errorScore + CASE WHEN @HasTC = 1 AND @TranspCost = 0 THEN 1 ELSE 0 END,
			   @valid       =               CASE WHEN @HasTC = 1 AND @TranspCost = 0 THEN 0 ELSE @valid END
  
		
		---------------------------------------------	
		-- inserisco costi per PROVVIGIONI
		---------------------------------------------
		IF (@QuoteType = 'R') OR (@QuoteType = 'S')     -- SOLO se R o S prima leggo dai dati caricati negli ordini
		  BEGIN
			SELECT @Provvig = CONVERT(DECIMAL(9,6),ValPar) FROM dbo.QuoteSimPar 
			WHERE NomePar = 'ProvvCost' 
			  AND QuoteType=@QuoteType AND CodQuote=@CodQuote AND QuoteRev=@QuoteRev
		  END

		-- leggo da tabella agenti
		IF ISNULL(@Provvig, 0) = 0
		  BEGIN
			SELECT	@Provvig = ISNULL(a.QuotaProvvAg, 0)
			FROM	dbo.AgentsDet a
			INNER JOIN dbo.ClientDet c ON a.CodAg = c.CodAg
			INNER JOIN dbo.QuoteList q ON q.CodClient = c.CodClient
			WHERE	q.QuoteType	= @QuoteType
				AND	q.CodQuote	= @CodQuote
				AND	q.QuoteRev	= @QuoteRev
		 END

		-- fix eventuali valori null
		SET @Provvig =  ISNULL(@Provvig, 0)

		-- inserisco costi per PROVVIGIONI
		INSERT INTO #QuoteOC(QuoteType, CodQuote, QuoteRev, ProcessNum, CodPlant, Class01,  Class02, TotQty, TotCost, Quota)
		SELECT	@QuoteType, @CodQuote, @QuoteRev, '04', @CodPlant, 'PROVVIGIONI', @RawMat, @BatchQty, ISNULL(@Provvig * @BatchQty, 0), 1

		/* ==================================================
			 CARICO TABELLE EFFETTIVE
		   ==================================================*/

		-- carico quote parametri!
		INSERT dbo.QuoteParam
		SELECT * FROM #QuoteParam

		-- carico lavorazioni INTERNE!
		INSERT dbo.QuoteWorkInt  -- ci sono valori calcolati quindi devo selezionare i campi
		SELECT QuoteType, CodQuote, QuoteRev, NumWI, ProcessNum, CodPlant, Class01, Class02, Class03, Class04, Class05
			 , NetProd, WSR, MSR, DSR, FC4UG, VC4UG, OH4UG, SC4UG, valid 
		FROM #QuoteWorkInt

		---- *** verifica errori ***
		SELECT DISTINCT @errorScore  = @errorScore + CASE WHEN TotQty = 0 THEN 1 ELSE 0 END,
						@valid       =               CASE WHEN TotQty = 0 THEN 0 ELSE @valid END
		FROM #QuoteOC

		---- carico OTHERCOSTS
		INSERT dbo.QuoteOC  -- ci sono valori calcolati quindi devo selezionare i campi
		SELECT QuoteType, CodQuote, QuoteRev, NumEx, ProcessNum, CodPlant, Class01, Class02
			 , Class03, Class04, Class05
			 , CASE TotQty WHEN 0 THEN 1 ELSE TotQty END   -- evito errore in campo calcolato se TotQty = 0
			 , TotCost, Quota, valid
		FROM #QuoteOC

		-- update valori di errore generale
		UPDATE	dbo.QuoteList
		SET		valid			= @valid
			  , errorScore		= @errorScore
		WHERE	QuoteType		= @QuoteType
			AND	CodQuote		= @CodQuote
			AND	QuoteRev		= @QuoteRev

	COMMIT TRAN;
	
	--SELECT COUNT(*) FROM #QuoteParam
	--SELECT COUNT(*) FROM #QuoteWorkInt
	--SELECT COUNT(*) FROM #QuoteOC

	-- elimino temp table... NON serve nella stored
	--IF OBJECT_ID('tempdb..#QuoteParam') IS NOT NULL
	--	DROP TABLE #QuoteParam
	--IF OBJECT_ID('tempdb..#QuoteWorkInt') IS NOT NULL
	--	DROP TABLE #QuoteWorkInt
	--IF OBJECT_ID('tempdb..#QuoteOC') IS NOT NULL
	--	DROP TABLE #QuoteOC

END
GO
PRINT N'Creating [dbo].[stp_QL_fullDataUpdate]...';


GO
-- =============================================
-- STORED PROCEDURE stp_QL_fullDataUpdate
--
-- Author:		Steamware
-- Create date: 2014.01.27
-- Description:	Recupera tutti i dati dalle tab QuoteList x avere schema x report/gestione web
-- =============================================
CREATE PROCEDURE [dbo].[stp_QL_fullDataUpdate] (
	  @QuoteType CHAR(1)    = 'Q'
	, @CodQuote BIGINT      = 0
	, @QuoteRev INT         = 0
	, @DoUpdate CHAR(1)     = 'N' -- se si debba fare ricalcolo Y/N
	)
AS
SET NOCOUNT ON

/* va rifatta struttura:
*
* tab temporanea
* calcolo parametri
* salvataggio in QuoteList dei 3 valori di sunto
* calcolo dei valori aggregati e restituzione riga risultati finali
*
*  ATTENZIONE NON CONTROLLA IL CAMPO VALID DEVE ESSERE SEMPRE 1 PER ESSERE VALIDO
*
*/


--DECLARE   @FullCost DECIMAL(9,6)
--        , @MinPrice DECIMAL(9,6)
IF (@DoUpdate = 'Y')
BEGIN
	EXEC dbo.stp_QL_update    @QuoteType
							, @CodQuote
							, @QuoteRev
END


-- inserire in tabelle: QuoteFull_Q (quotazioni/preventivi)
-- inserire in tabelle: QuoteFull_R (resoconto di commessa)
-- inserire in tabelle: QuoteFull_S (simulazioni)

-- elimino eventuale temp table...
IF OBJECT_ID('tempdb..#TempFullData') IS NOT NULL
	DROP TABLE #TempFullData;


-- Costruisco la "superselect" di tutti i valori necessari...

-- =================================================
-- PIVOT TABELLA QuoteParameter
-- =================================================
;WITH ctePivotQuoteP 
AS (
	SELECT *
	FROM (
			SELECT QuoteType
				, CodQuote
				, QuoteRev
				, Descr
				, Parameter
			FROM dbo.QuoteParam
			WHERE CodQuote = @CodQuote AND QuoteType = @QuoteType AND QuoteRev = @QuoteRev
		) AS SourceTable

	PIVOT(MIN(Parameter) FOR Descr IN (
		  ItemDescr
		, CodifProfilo
		, ClasseMerc
		, CodClientAssoc
		, ClientNameAssoc
		, CodDiesGroup
		, TipoDies
		, DiamDies
		, HoleNumDies
		, NumDiesInList
		, NumDiesExaust
		, CodPlant
		, KeyAM
		, KeyAMIL
		, NumSMED
		, KgTeo
		, KgProdotti
		, QuotaMan
		, DiesPrice
		, DiesExpLife
		, DiesEOLife
		, DiesByClass
		, PkgDesc
		, PRMWeight
		, PWeight
		, PTare
		, TareStRatio
		, LivPackage
		, LivPackageDett
		-- START nuovi campi x SIM
		, DiesPrice_sim
		, SamplePrice
		, DiesFullCost
		, DiesPriceClientQuote
		, DiesTecLife
		, DiesCommLife
		, MonthSalesPrev
		, SalesPrevCost
		, DiesFinCost
		, ClientQuoteReven
		, ExtraDiscountDies
		, WSR01_sim
		, MSR01_sim
		, NetProd01_sim
		, NetProd04_sim
		, DSR_sim
		-- end nuovi campi x SIM
		)
  ) AS PivotData
),
-- =================================================
-- PIVOT TABELLA QuoteOC
-- =================================================
ctePivotQuoteOC AS (   
	SELECT *
	FROM (
			SELECT    QuoteType
					, CodQuote
					, QuoteRev
					, Class01 + ProcessNum AS ClassProc
					, C4UG
			FROM dbo.QuoteOC
			WHERE CodQuote = @CodQuote AND QuoteType = @QuoteType AND QuoteRev = @QuoteRev
			) AS SourceTable
	PIVOT(SUM(C4UG) FOR ClassProc IN 
			  (   EE01
				, GAS01
				, MATRICE01
				, VENDITA01
				, ROTTAME01
				, VENDITA04
				, ROTTAME04
				, IMBALLO04
				, TRASPORTI04
				, PROVVIGIONI04
			  ) 
	   ) AS PivotData
)
-- =================================================
-- MAIN Select Tabella con INTO temp table
-- =================================================
SELECT 'V14.1' AS Vers
	, QL.QuoteType
	, QL.CodQuote
	, QL.QuoteRev
	, QL.IdxQState
	, QL.CodClient
	, ISNULL(CD.ClientName,N'') AS ClientName
	, QL.CodItem
	, QL.CodItemGroup
	, QL.RawMat
	, QL.UnitWeight
	, QL.BatchQty
	, QL.CodInco
	, ISNULL(CD.TranspZone,N'') AS TranspZone
	, QL.KeyAM
	, QL.Note
	, QL.PriceOff
	, QL.OrdDate
	, QL.OrdNum
	, QL.OrdRow
	, QL.OrdPrice
	, QL.OrdQty
	, pQP.CodClientAssoc
	, pQP.ClientNameAssoc
	, pQP.ItemDescr
	, pQP.CodifProfilo
	, pQP.ClasseMerc
	, pQP.TipoDies
	, pQP.CodDiesGroup
	, CONVERT(DECIMAL(18,6),pQP.DiamDies)               AS DiamDies
	, CONVERT(INT,pQP.HoleNumDies)                      AS HoleNumDies
	, ISNULL(CONVERT(DECIMAL(18,6),pQP.DiesPrice),0)    AS DiesPrice
	, CONVERT(DECIMAL(18,6),pQP.DiesExpLife)            AS DiesExpLife
	, CONVERT(DECIMAL(18,6),pQP.DiesEOLife)             AS DiesEOLife
	, CONVERT(BIT, ISNULL(pQP.DiesByClass,0))           AS DiesByClass
	, CONVERT(DECIMAL(18,6),pQP.NumDiesInList)          AS NumDiesInList
	, CONVERT(DECIMAL(18,6),pQP.NumDiesExaust)          AS NumDiesExaust
	, pQP.CodPlant
	, pQP.KeyAMIL
	, CONVERT(DECIMAL(18,6),pQP.KgTeo)                  AS KgTeo
	, CONVERT(DECIMAL(18,6),pQP.NumSMED)                AS NumSMED
	, CONVERT(DECIMAL(18,6),pQP.QuotaMan)               AS QuotaMan
	, CONVERT(DECIMAL(18,6),pQP.PRMWeight)              AS PRMWeight
	, CONVERT(DECIMAL(18,6),pQP.PWeight)                AS PWeight
	, CONVERT(DECIMAL(18,6),pQP.PTare)                  AS PTare
	, pQP.LivPackage
	, pQP.LivPackageDett
	-- START nuovi campi x SIM
	, ISNULL(CONVERT(DECIMAL(18,6),pQP.DiesPrice_sim),0)            AS DiesPrice_sim
	, ISNULL(CONVERT(DECIMAL(18,6),pQP.SamplePrice),0)              AS SamplePrice
	, ISNULL(CONVERT(DECIMAL(18,6),pQP.DiesFullCost),0)             AS DiesFullCost
	, ISNULL(CONVERT(DECIMAL(18,6),pQP.DiesPriceClientQuote),0)     AS DiesPriceClientQuote
	, ISNULL(CONVERT(DECIMAL(18,6),pQP.DiesTecLife),0)              AS DiesTecLife
	, ISNULL(CONVERT(DECIMAL(18,6),pQP.DiesCommLife),1)             AS DiesCommLife
	, ISNULL(CONVERT(INT,pQP.MonthSalesPrev),0)                     AS MonthSalesPrev
	, ISNULL(CONVERT(DECIMAL(18,6),pQP.SalesPrevCost),0)            AS SalesPrevCost
	, ISNULL(CONVERT(DECIMAL(18,6),pQP.DiesFinCost),0)              AS DiesFinCost
	, ISNULL(CONVERT(DECIMAL(18,6),pQP.ClientQuoteReven),0)         AS ClientQuoteReven
	, ISNULL(CONVERT(DECIMAL(18,6),pQP.ExtraDiscountDies),0)        AS ExtraDiscountDies
	, ISNULL(CONVERT(DECIMAL(9,8),pQP.WSR01_sim),0)                 AS WSR01_sim
	, ISNULL(CONVERT(DECIMAL(9,8),pQP.MSR01_sim),0)                 AS MSR01_sim
	, ISNULL(CONVERT(DECIMAL(9,3),pQP.NetProd01_sim),0)             AS NetProd01_sim
	, ISNULL(CONVERT(DECIMAL(9,3),pQP.NetProd04_sim),0)             AS NetProd04_sim
	, ISNULL(CONVERT(DECIMAL(9,8),pQP.DSR_sim),0)                  AS DSR_sim
	-- end nuovi campi x SIM
	, QRM.RawMatCost
	, QRM.RawMatExtraCost
	, QRM.RawMatCost + QRM.RawMatExtraCost AS RawMatFullCost -- fare campo calcolato ?!?
	, QRM.CodPackag
	, pQP.PkgDesc
	, QRM.FSR
	, ISNULL(pQOC.PROVVIGIONI04, 0) AS ProvvCost
	, ISNULL(pQOC.EE01, 0)          AS EECost
	, ISNULL(pQOC.GAS01, 0)         AS GasCost
	, ISNULL(pQOC.MATRICE01, 0)     AS DiesCost
	, ISNULL(pQOC.IMBALLO04, 0)     AS PackCost
	, ISNULL(pQOC.TRASPORTI04, 0)   AS TranspCost
	, ISNULL(pQOC.VENDITA01, 0)     AS SellCost01
	, ISNULL(pQOC.ROTTAME01, 0)     AS RefCost01
	, ISNULL(pQOC.VENDITA04, 0)     AS SellCost04
	, ISNULL(pQOC.ROTTAME04, 0)     AS RefCost04
	, QWI01.WSR                     AS WSR01
	, QWI01.MSR                     AS MSR01
	, QWI01.NetProd                 AS NetProd01
	, QWI01.FC4UG                   AS FC4UG01
	, QWI01.VC4UG                   AS VC4UG01
	, QWI01.OH4UG                   AS OH4UG01
	, QWI01.SC4UG                   AS SC4UG01
	, 1 - (QWI01.DYR * QWI02.DYR * QWI03.DYR * QWI04.DYR) AS DSR
	, QWI04.NetProd                 AS NetProd04
	, QWI04.FC4UG                   AS FC4UG04
	, QWI04.VC4UG                   AS VC4UG04
	, ISNULL(pQOC.VENDITA01, 0) + ISNULL(pQOC.ROTTAME01, 0) + ISNULL(pQOC.VENDITA04, 0) + ISNULL(pQOC.ROTTAME04, 0) + ISNULL(pQOC.EE01, 0) + ISNULL(pQOC.GAS01, 0) + ISNULL(pQOC.MATRICE01, 0) + ISNULL(pQOC.IMBALLO04, 0) + ISNULL(pQOC.PROVVIGIONI04, 0) + ISNULL(pQOC.TRASPORTI04, 0) + QWI01.VC4UG + QWI04.VC4UG + QWI01.SC4UG AS FVC
	, PD.Charge
	, QL.valid
	, QL.errorScore

INTO #TempFullData      -- carico in temp table
FROM dbo.QuoteList AS QL

LEFT JOIN dbo.ClientDet CD              -- non voglio che non crei record x mancanza Cliente
	ON QL.CodClient = CD.CodClient

INNER JOIN ctePivotQuoteP AS pQP
	ON      QL.QuoteType = pQP.QuoteType
		AND QL.CodQuote  = pQP.CodQuote
		AND QL.QuoteRev  = pQP.QuoteRev

INNER JOIN dbo.QuoteRM AS QRM
	ON      QL.QuoteType = QRM.QuoteType
		AND QL.CodQuote  = QRM.CodQuote
		AND QL.QuoteRev  = QRM.QuoteRev
		AND QL.rawmat    = QRM.RawMat

INNER JOIN  ctePivotQuoteOC AS pQOC
		ON      QL.QuoteType = pQOC.QuoteType
			AND QL.CodQuote  = pQOC.CodQuote
			AND QL.QuoteRev  = pQOC.QuoteRev

INNER JOIN dbo.QuoteWorkInt AS QWI01
	ON      QL.QuoteType = QWI01.QuoteType
		AND QL.CodQuote  = QWI01.CodQuote
		AND QL.QuoteRev  = QWI01.QuoteRev
		AND QWI01.ProcessNum = '01'
INNER JOIN dbo.QuoteWorkInt AS QWI02
	ON      QL.QuoteType = QWI02.QuoteType
		AND QL.CodQuote  = QWI02.CodQuote
		AND QL.QuoteRev  = QWI02.QuoteRev
		AND QWI02.ProcessNum = '02'
INNER JOIN dbo.QuoteWorkInt AS QWI03
	ON      QL.QuoteType = QWI03.QuoteType
		AND QL.CodQuote  = QWI03.CodQuote
		AND QL.QuoteRev  = QWI03.QuoteRev
		AND QWI03.ProcessNum = '03'
INNER JOIN dbo.QuoteWorkInt AS QWI04
	ON      QL.QuoteType = QWI04.QuoteType
		AND QL.CodQuote  = QWI04.CodQuote
		AND QL.QuoteRev  = QWI04.QuoteRev
		AND QWI04.ProcessNum = '04'
INNER JOIN dbo.PlantsDet AS PD
	ON PD.CodPlant = pQP.CodPlant


-- 2014.09.10 modifica x proporre campi _sim a standard...
-- Campi _sim: faccio verifica, se fossero vuoti li metto pari agli equivalenti NON _sim
UPDATE  #TempFullData
    SET WSR01_sim = CASE WHEN WSR01_sim > 0 THEN WSR01_sim ELSE WSR01 END
      , MSR01_sim = CASE WHEN MSR01_sim > 0 THEN MSR01_sim ELSE MSR01 END
      , DSR_sim = CASE WHEN DSR_sim > 0 THEN DSR_sim ELSE DSR END
      , NetProd01_sim = CASE WHEN NetProd01_sim > 0 THEN NetProd01_sim ELSE NetProd01 END
      , NetProd04_sim = CASE WHEN NetProd04_sim > 0 THEN NetProd04_sim ELSE NetProd04 END

---- salvo i dati dell'ordine: FullCost, MinPrice, PriceOff (se zero lo pongo uguale a MinPrice)
--UPDATE  QuoteList
--SET     FullCost    = @FullCost
--        , MinPrice  = @MinPrice
--        , PriceOff  = CASE WHEN ISNULL(PriceOff,0) = 0 THEN @MinPrice ELSE PriceOff END
--WHERE   QuoteType = @QuoteType
--	AND CodQuote = @CodQuote
--	AND QuoteRev = @QuoteRev

-- SELECT TOP 1000 * FROM #TempFullData

IF @QuoteType = 'Q' 
 BEGIN 
	IF OBJECT_ID('QuoteFull_Q') IS NULL             -- CREATE TABLE QuoteFull_Q da eliminare quando Tabella Definitiva
		SELECT * INTO dbo.QuoteFull_Q FROM #TempFullData
	ELSE
	 BEGIN
		--DELETE dbo.QuoteFull_Q WHERE QuoteType = @QuoteType AND CodQuote = @CodQuote AND QuoteRev = @QuoteRev
		DELETE dbo.QuoteFull_Q WHERE QuoteType = @QuoteType AND CodQuote = @CodQuote AND QuoteRev = @QuoteRev
		INSERT INTO dbo.QuoteFull_Q (Vers, QuoteType, CodQuote, QuoteRev, IdxQState, CodClient, ClientName, CodItem, CodItemGroup, RawMat, UnitWeight, BatchQty, CodInco, TranspZone, KeyAM, Note, PriceOff, CodClientAssoc, ClientNameAssoc, ItemDescr, CodifProfilo, ClasseMerc, TipoDies, CodDiesGroup, DiamDies, HoleNumDies, DiesPrice, DiesExpLife, DiesEOLife, DiesByClass, NumDiesInList, NumDiesExaust, CodPlant, KeyAMIL, KgTeo, NumSMED, QuotaMan, PRMWeight, PWeight, PTare, LivPackage, LivPackageDett, RawMatCost, RawMatExtraCost, RawMatFullCost, CodPackag, PkgDesc, FSR, ProvvCost, EECost, GasCost, DiesCost, PackCost, TranspCost, SellCost01, RefCost01, SellCost04, RefCost04, WSR01, MSR01, NetProd01, FC4UG01, VC4UG01, OH4UG01, SC4UG01, DSR, NetProd04, FC4UG04, VC4UG04, FVC, Charge, valid, errorScore)
		SELECT Vers, QuoteType, CodQuote, QuoteRev, IdxQState, CodClient, ClientName, CodItem, CodItemGroup, RawMat, UnitWeight, BatchQty, CodInco, TranspZone, KeyAM, Note, PriceOff, CodClientAssoc, ClientNameAssoc, ItemDescr, CodifProfilo, ClasseMerc, TipoDies, CodDiesGroup, DiamDies, HoleNumDies, DiesPrice, DiesExpLife, DiesEOLife, DiesByClass, NumDiesInList, NumDiesExaust, CodPlant, KeyAMIL, KgTeo, NumSMED, QuotaMan, PRMWeight, PWeight, PTare, LivPackage, LivPackageDett, RawMatCost, RawMatExtraCost, RawMatFullCost, CodPackag, PkgDesc, FSR, ProvvCost, EECost, GasCost, DiesCost, PackCost, TranspCost, SellCost01, RefCost01, SellCost04, RefCost04, WSR01, MSR01, NetProd01, FC4UG01, VC4UG01, OH4UG01, SC4UG01, DSR, NetProd04, FC4UG04, VC4UG04, FVC, Charge, valid, errorScore
		FROM    #TempFullData
	 END
 END

ELSE IF @QuoteType = 'R'
 BEGIN 
	IF OBJECT_ID('QuoteFull_R') IS NULL             -- CREATE TABLE QuoteFull_R da eliminare quando Tabella Definitiva
		SELECT * INTO dbo.QuoteFull_R FROM #TempFullData
	ELSE
	 BEGIN
		DELETE dbo.QuoteFull_R WHERE QuoteType = @QuoteType AND CodQuote = @CodQuote AND QuoteRev = @QuoteRev
		INSERT INTO dbo.QuoteFull_R (Vers, QuoteType, CodQuote, QuoteRev, IdxQState, CodClient, ClientName, CodItem, CodItemGroup, RawMat, UnitWeight, BatchQty, CodInco, TranspZone, KeyAM, Note, PriceOff, CodClientAssoc, ClientNameAssoc, ItemDescr, CodifProfilo, ClasseMerc, TipoDies, CodDiesGroup, DiamDies, HoleNumDies, DiesPrice, DiesExpLife, DiesEOLife, DiesByClass, NumDiesInList, NumDiesExaust, CodPlant, KeyAMIL, KgTeo, NumSMED, QuotaMan, PRMWeight, PWeight, PTare, LivPackage, LivPackageDett, RawMatCost, RawMatExtraCost, RawMatFullCost, CodPackag, PkgDesc, FSR, ProvvCost, EECost, GasCost, DiesCost, PackCost, TranspCost, SellCost01, RefCost01, SellCost04, RefCost04, WSR01, MSR01, NetProd01, FC4UG01, VC4UG01, OH4UG01, SC4UG01, DSR, NetProd04, FC4UG04, VC4UG04, FVC, Charge, OrdDate, OrdNum, OrdRow, OrdPrice, OrdQty, valid, errorScore)
		SELECT Vers, QuoteType, CodQuote, QuoteRev, IdxQState, CodClient, ClientName, CodItem, CodItemGroup, RawMat, UnitWeight, BatchQty, CodInco, TranspZone, KeyAM, Note, PriceOff, CodClientAssoc, ClientNameAssoc, ItemDescr, CodifProfilo, ClasseMerc, TipoDies, CodDiesGroup, DiamDies, HoleNumDies, DiesPrice, DiesExpLife, DiesEOLife, DiesByClass, NumDiesInList, NumDiesExaust, CodPlant, KeyAMIL, KgTeo, NumSMED, QuotaMan, PRMWeight, PWeight, PTare, LivPackage, LivPackageDett, RawMatCost, RawMatExtraCost, RawMatFullCost, CodPackag, PkgDesc, FSR, ProvvCost, EECost, GasCost, DiesCost, PackCost, TranspCost, SellCost01, RefCost01, SellCost04, RefCost04, WSR01, MSR01, NetProd01, FC4UG01, VC4UG01, OH4UG01, SC4UG01, DSR, NetProd04, FC4UG04, VC4UG04, FVC, Charge, OrdDate, OrdNum, OrdRow, OrdPrice, OrdQty, valid, errorScore
--        FROM [dbo].[v_pivot]
		FROM    #TempFullData
	 END
 END

ELSE IF @QuoteType = 'S'
 BEGIN 
	IF OBJECT_ID('QuoteFull_S') IS NULL             -- CREATE TABLE QuoteFull_S da eliminare quando Tabella Definitiva
		SELECT * INTO dbo.QuoteFull_S FROM #TempFullData
	ELSE
	 BEGIN     
		DELETE dbo.QuoteFull_S WHERE QuoteType = @QuoteType AND CodQuote = @CodQuote AND QuoteRev = @QuoteRev
		INSERT INTO dbo.QuoteFull_S (Vers, QuoteType, CodQuote, QuoteRev, IdxQState, CodClient, ClientName, CodItem, CodItemGroup, RawMat, UnitWeight, BatchQty, CodInco, TranspZone, KeyAM, Note, PriceOff, CodClientAssoc, ClientNameAssoc, ItemDescr, CodifProfilo, ClasseMerc, TipoDies, CodDiesGroup, DiamDies, HoleNumDies, DiesPrice_sim, DiesPrice, SamplePrice, DiesFullCost, DiesPriceClientQuote, DiesExpLife, DiesEOLife, DiesTecLife, DiesCommLife, MonthSalesPrev, SalesPrevCost, DiesFinCost, ClientQuoteReven, ExtraDiscountDies, DiesByClass, NumDiesInList, NumDiesExaust, CodPlant, KeyAMIL, KgTeo, NumSMED, QuotaMan, PRMWeight, PWeight, PTare, LivPackage, LivPackageDett, RawMatCost, RawMatExtraCost, RawMatFullCost, CodPackag, PkgDesc, FSR, ProvvCost, EECost, GasCost, DiesCost, PackCost, TranspCost, SellCost01, RefCost01, SellCost04, RefCost04, WSR01_sim, WSR01, MSR01_sim, MSR01, NetProd01_sim, NetProd01, FC4UG01, VC4UG01, OH4UG01, SC4UG01, DSR_sim, DSR, NetProd04_sim, NetProd04, FC4UG04, VC4UG04, FVC, Charge, valid, errorScore)
		SELECT  Vers, QuoteType, CodQuote, QuoteRev, IdxQState, CodClient, ClientName, CodItem, CodItemGroup, RawMat, UnitWeight, BatchQty, CodInco, TranspZone, KeyAM, Note, PriceOff, CodClientAssoc, ClientNameAssoc, ItemDescr, CodifProfilo, ClasseMerc, TipoDies, CodDiesGroup, DiamDies, HoleNumDies, DiesPrice_sim, DiesPrice, SamplePrice, (DiesPrice_sim + SamplePrice) AS DiesFullCost, DiesPriceClientQuote, DiesExpLife, DiesEOLife, DiesTecLife, DiesCommLife, MonthSalesPrev
				-- se DiesCommLife è NULLA è messa a 1 sopra
				,CASE WHEN ( DiesTecLife = 0 OR DiesCommLife = 0 ) 
					  THEN 0
					  ELSE ( (((DiesTecLife % DiesCommLife) / DiesTecLife) * ( DiesPrice_sim + SamplePrice) ) / DiesTecLife )
				 END AS SalesPrevCost
				,CASE WHEN DiesCommLife > 0
					  THEN ((((DiesPrice_sim+SamplePrice)-DiesPriceClientQuote)*(power((1.05),MonthSalesPrev/(12))-(1))) / DiesCommLife )
					  ELSE ((((DiesPrice_sim+SamplePrice)-DiesPriceClientQuote)*(power((1.05),MonthSalesPrev/(12))-(1))) / 1            )
				 END AS DiesFinCost
				,CASE WHEN DiesTecLife > 0
					  THEN ( -DiesPriceClientQuote / DiesTecLife )
					  ELSE -DiesPriceClientQuote
				 END AS ClientQuoteReven
				,CASE WHEN ( DiesTecLife = 0 OR DiesCommLife = 0 )
					  THEN 0
					  ELSE  (((((DiesTecLife % DiesCommLife) / DiesTecLife ) * (DiesPrice_sim+SamplePrice)) /  DiesTecLife 
						   +(((DiesPrice_sim+SamplePrice)-DiesPriceClientQuote) * (power((1.05),MonthSalesPrev/(12))-(1))) / DiesCommLife )
						   - DiesPriceClientQuote / DiesTecLife ) 
					END AS ExtraDiscountDies

				-- CALCOLI OLD Version
				--((((DiesTecLife%DiesCommLife)/case when DiesTecLife=(0) then (1) else DiesTecLife end)*(DiesPrice+SamplePrice))/case when DiesTecLife=(0) then (1) else DiesTecLife end) AS SalesPrevCost, 
				--((((DiesPrice+SamplePrice)-DiesPriceClientQuote)*(power((1.05),MonthSalesPrev/(12))-(1)))/case when DiesCommLife>(0) then DiesCommLife else (1) end) AS DiesFinCost, 
				--( -DiesPriceClientQuote/case when DiesTecLife>(0) then DiesTecLife else (1) end) AS ClientQuoteReven, 
				--(((((DiesTecLife%DiesCommLife)/case when DiesTecLife=(0) then (1) else DiesTecLife end)*(DiesPrice+SamplePrice))/case when DiesTecLife=(0) then (1) else DiesTecLife end+(((DiesPrice+SamplePrice)-DiesPriceClientQuote)*(power((1.05),MonthSalesPrev/(12))-(1)))/case when DiesCommLife>(0) then DiesCommLife else (1) end)-DiesPriceClientQuote/case when DiesTecLife>(0) then DiesTecLife else (1) end) AS ExtraDiscountDies, 

				,DiesByClass, NumDiesInList, NumDiesExaust, CodPlant, KeyAMIL, KgTeo, NumSMED, QuotaMan, PRMWeight, PWeight, PTare, LivPackage, LivPackageDett, RawMatCost, RawMatExtraCost, RawMatFullCost, CodPackag, PkgDesc, FSR, ProvvCost, EECost, GasCost, DiesCost, PackCost, TranspCost, SellCost01, RefCost01, SellCost04, RefCost04, WSR01_sim, WSR01, MSR01_sim, MSR01, NetProd01_sim, NetProd01, FC4UG01, VC4UG01, OH4UG01, SC4UG01, DSR_sim, DSR, NetProd04_sim, NetProd04, FC4UG04, VC4UG04, FVC, Charge, valid, errorScore

		FROM    #TempFullData
	 END
 END
ELSE IF @QuoteType = 'C'
 BEGIN 
		DELETE dbo.QuoteFull_C WHERE QuoteType = @QuoteType AND CodQuote = @CodQuote AND QuoteRev = @QuoteRev
		INSERT INTO dbo.QuoteFull_C ( Vers, QuoteType, CodQuote, QuoteRev, Class01, Class02, CodItem, RawMat, CodPlant, CodDiesGroup, CodPackag, batchQty, CodInco, RawMatFullCost, FVC, FullCost, valid, errorScore )
		SELECT                        Vers, QuoteType, CodQuote, QuoteRev, CodifProfilo, ClasseMerc, tmp.CodItem, RawMat, tmp.CodPlant, CodDiesGroup, CodPackag, batchQty, CodInco, RawMatFullCost, FVC, FVC + FC4UG01 + OH4UG01 + FC4UG04 AS FullCost, valid, errorScore
		FROM  #TempFullData AS tmp
END

-- elimino temp table...
--IF OBJECT_ID('tempdb..#TempFullData') IS NOT NULL
--    DROP TABLE #TempFullData

RETURN
GO
PRINT N'Creating [dbo].[stp_QL_fullDataSearch]...';


GO
-- =============================================
-- STORED PROCEDURE stp_QL_fullDataSearch
--
-- Author:		Steamware
-- Mod date: 2014.02.11
-- Description:	Recupera tutti i dati dalle tab QuoteList x avere schema con ricerca x cliente, item, materiale
-- =============================================
CREATE PROCEDURE [dbo].[stp_QL_fullDataSearch]
(
	  @CodClient	NVARCHAR(50) = ''
	, @CodItem		NVARCHAR(50) = ''
	, @RawMat		NVARCHAR(50) = ''
	, @DataMin		DATETIME
	, @DataMax		DATETIME
	, @qtaMin		INT = 0
	, @qtaMax		INT = 999999
	, @QuoteType	CHAR(1) = '*'
	, @IdxQState	INT = '-1'
	, @search		NVARCHAR(250) = '*'
)
AS
SET NOCOUNT ON

-- cte x selezionare solo ultime revisioni...
;WITH myCte AS
(
	SELECT		QuoteType, CodQuote, MAX(QuoteRev) AS QuoteRev
	FROM		QuoteList
	GROUP BY	QuoteType, CodQuote
),
qfq_filt AS
(
	SELECT	*	
	FROM	v_QuoteFull_Q
	WHERE	ClientName LIKE CASE WHEN @search <> '*' THEN '%'+@search+'%' ELSE ClientName END
		OR	RawMat LIKE CASE WHEN @search <> '*' THEN '%'+@search+'%' ELSE RawMat END
		OR	CodItem LIKE CASE WHEN @search <> '*' THEN '%'+@search+'%' ELSE CodItem END
		OR	CONVERT(NVARCHAR(30), CodQuote) LIKE CASE WHEN @search <> '*' THEN '%'+@search+'%' ELSE CONVERT(NVARCHAR(30), CodQuote) END
)
-- calcolo con aggiunta campi sommati...
SELECT vq.*	
FROM qfq_filt vq
	INNER JOIN myCte mc ON vq.QuoteType = mc.QuoteType AND vq.CodQuote = mc.CodQuote AND vq.QuoteRev = mc.QuoteRev
WHERE	vq.CodClient = CASE WHEN ISNULL(@CodClient,'') = '' THEN vq.CodClient ELSE @CodClient END
	AND vq.CodItem = CASE WHEN ISNULL(@CodItem,'') = '' THEN vq.CodItem ELSE @CodItem END
	AND vq.RawMat = CASE WHEN ISNULL(@RawMat,'') = '' THEN vq.RawMat ELSE @RawMat END
	AND vq.CodQuote BETWEEN CONVERT(NVARCHAR(30), @DataMin, 12)*10000 AND (CONVERT(NVARCHAR(30), @DataMax, 12) +1 )*10000 
	AND	vq.BatchQty BETWEEN @qtaMin AND @qtaMax
	AND vq.QuoteType = CASE WHEN @QuoteType = '*' THEN vq.QuoteType ELSE @QuoteType END
	AND vq.IdxQState = CASE WHEN @IdxQState = -1 THEN vq.IdxQState ELSE @IdxQState END

--	AND vq.ClientName LIKE '%{0}%' OR RawMat LIKE '%{0}%' OR CodItem LIKE '%{0}%' OR CONVERT(CodQuote, 'System.String') LIKE '%{0}%'


ORDER BY	CodQuote DESC

RETURN
GO
PRINT N'Creating [dbo].[stp_QL_fullData]...';


GO
-- =============================================
-- STORED PROCEDURE stp_QL_fullData
--
-- Author:		Steamware
-- Create date: 2014.01.27
-- Description:	Recupera tutti i dati dalle tab QuoteList x avere schema x report/gestioen web
-- =============================================
CREATE PROCEDURE [dbo].[stp_QL_fullData] (
	@QuoteType CHAR(1) = 'Q'
	, @CodQuote BIGINT = 0
	, @QuoteRev INT = 0
	, @DoUpdate CHAR(1) = 'N' -- se si debba fare ricalcolo Y/N
	)
AS
SET NOCOUNT ON

IF(@QuoteType <> '' AND @DoUpdate = 'N')
BEGIN
	EXEC stp_QL_fullDataUpdate @QuoteType
		, @CodQuote
		, @QuoteRev
		, @DoUpdate
END

---- calcolo con aggiunta campi sommati...
--SELECT *
--	, FVC + RawMatFullCost AS P_FVC
--	, FC4UG01 + OH4UG01 AS CPS
--	, FC4UG01 + OH4UG01 + FVC + RawMatFullCost AS P_CPS
--	, FC4UG04 + FVC + RawMatFullCost AS P_FC4UG04
--	, FVC + FC4UG01 + OH4UG01 + FC4UG04 AS FullCost
--	, FVC + FC4UG01 + OH4UG01 + FC4UG04 + RawMatFullCost AS P_FullCost
--	, Charge * (FVC + FC4UG01 + OH4UG01 + FC4UG04) AS MinPrice
--	, Charge * (FVC + FC4UG01 + OH4UG01 + FC4UG04) + RawMatFullCost AS P_MinPrice
--	, PriceOff + RawMatFullCost AS P_PriceOff
--	, (FVC + FC4UG01 + OH4UG01 + FC4UG04) - PriceOff AS NetMar
--	, (PriceOff - FVC) / (FC4UG01 + OH4UG01 + FC4UG04) AS FCShield
--	, (PRMWeight - Ptare) * (PriceOff + RawMatFullCost) / Pweight AS PckSur
--FROM QuoteFull_Q
--WHERE QuoteType = @QuoteType
--	AND CodQuote = @CodQuote
--	AND QuoteRev = @QuoteRev

-- calcolo con aggiunta campi sommati...
SELECT *	
FROM v_QuoteFull_Q
WHERE QuoteType = @QuoteType
	AND CodQuote = @CodQuote
	AND QuoteRev = @QuoteRev

RETURN
GO
PRINT N'Creating [dbo].[stp_prt_dsQuoteFull_byChiave]...';


GO
-- =============================================
-- STORED PROCEDURE stp_prt_dsQuoteFull_Q_Data
--
-- Author:		Steamware
-- Mod date: 2014.05.23
-- Description:	dataset stp_prt_dsQuoteFull_Q_Data per reportOffers 
-- =============================================
CREATE PROCEDURE [dbo].[stp_prt_dsQuoteFull_byChiave]
(
    @Chiave AS NVARCHAR(50) = ''
)
AS
BEGIN
    SET NOCOUNT ON;

/*
    Se decidiamo di separare le traduzioni dei lemmi tra Applicazione e stampa basta usare la prima cte come insert 
    nella tabella vocabolario e poi sostituire la cte con la tabella vocabolario stessa
*/

SELECT 
       -- chiave
      Vers
	, QuoteType
	, CodQuote
	, QuoteRev
      -- valori
	, IdxQState
	, CodClient
	, ClientName
	, CodItem
	, CodItemGroup
	, RawMat
	, UnitWeight
	, BatchQty
	, CodInco
	, TranspZone
	, KeyAM
	, Note
	, PriceOff
	, CodClientAssoc
	, ClientNameAssoc
	, ItemDescr
	, CodifProfilo
	, ClasseMerc
	, TipoDies
	, CodDiesGroup
	, DiamDies
	, HoleNumDies
	, DiesPrice
	, DiesExpLife
	, DiesEOLife
	, DiesByClass
	, NumDiesInList
	, NumDiesExaust
	, CodPlant
	, KeyAMIL
	, KgTeo
	, NumSMED
	, QuotaMan
	, PRMWeight
	, PWeight
	, PTare
	, LivPackage
	, LivPackageDett
	, RawMatCost
	, RawMatExtraCost
	, RawMatFullCost
	, CodPackag
	, PkgDesc
	, FSR
	, ProvvCost
	, EECost
	, GasCost
	, DiesCost
	, PackCost
	, TranspCost
	, SellCost01
	, RefCost01
	, SellCost04
	, RefCost04
	, WSR01
	, MSR01
	, NetProd01
	, FC4UG01
	, VC4UG01
	, OH4UG01
	, SC4UG01
	, DSR
	, NetProd04
	, FC4UG04
	, VC4UG04
	, FVC
	, Charge
	, P_FVC
	, CPS
	, P_CPS
	, P_FC4UG04
	, FullCost
	, P_FullCost
	, MinPrice
	, P_MinPrice
	, P_PriceOff
	, NetMar
	, FCShield
	, PckSur
	, valid
	, errorScore
	, DiesPrice_sim
	, SamplePrice
	, DiesFullCost
	, DiesPriceClientQuote
	, DiesTecLife
	, DiesCommLife
	, MonthSalesPrev
	, SalesPrevCost
	, DiesFinCost
	, ClientQuoteReven
	, ExtraDiscountDies
	, WSR01_sim
	, MSR01_sim
	, NetProd01_sim
	, NetProd04_sim
	, DSR_sim
	, NetMar_sim
	, FCShield_sim
	, MinPrice_sim
	, P_MinPrice_sim

FROM dbo.v_QuoteFull_Q
WHERE	QuoteType = dbo.f_prt_getParameter ( 'QuoteType', @Chiave , '&')
    AND CodQuote  = dbo.f_prt_getParameter ( 'CodQuote' , @Chiave , '&')
    AND QuoteRev  = dbo.f_prt_getParameter ( 'QuoteRev' , @Chiave +'&' , '&')


END
GO
PRINT N'Creating [dbo].[stp_prt_dsQuoteFull_Q_Data]...';


GO
-- =============================================
-- STORED PROCEDURE stp_prt_dsQuoteFull_Q_Data
--
-- Author:		Steamware
-- Mod date:    2014.04.28
-- Description:	dataset stp_prt_dsQuoteFull_Q_Data per reportOffers 
-- =============================================
CREATE PROCEDURE [dbo].[stp_prt_dsQuoteFull_Q_Data]
    @Ticket AS INT = 1
AS
BEGIN
    SET NOCOUNT ON;

/*
    Se decidiamo di separare le traduzioni dei lemmi tra Applicazione e stampa basta usare la prima cte come insert 
    nella tabella vocabolario e poi sostituire la cte con la tabella vocabolario stessa
*/

SELECT 
       -- chiave
      Vers
	, QuoteType
	, CodQuote
	, QuoteRev
      -- valori
	, IdxQState
	, CodClient
	, ClientName
	, CodItem
	, CodItemGroup
	, RawMat
	, UnitWeight
	, BatchQty
	, CodInco
	, TranspZone
	, KeyAM
	, Note
	, PriceOff
	, CodClientAssoc
	, ClientNameAssoc
	, ItemDescr
	, CodifProfilo
	, ClasseMerc
	, TipoDies
	, CodDiesGroup
	, DiamDies
	, HoleNumDies
	, DiesPrice
	, DiesExpLife
	, DiesEOLife
	, DiesByClass
	, NumDiesInList
	, NumDiesExaust
	, CodPlant
	, KeyAMIL
	, KgTeo
	, NumSMED
	, QuotaMan
	, PRMWeight
	, PWeight
	, PTare
	, LivPackage
	, LivPackageDett
	, RawMatCost
	, RawMatExtraCost
	, RawMatFullCost
	, CodPackag
	, PkgDesc
	, FSR
	, ProvvCost
	, EECost
	, GasCost
	, DiesCost
	, PackCost
	, TranspCost
	, SellCost01
	, RefCost01
	, SellCost04
	, RefCost04
	, WSR01
	, MSR01
	, NetProd01
	, FC4UG01
	, VC4UG01
	, OH4UG01
	, SC4UG01
	, DSR
	, NetProd04
	, FC4UG04
	, VC4UG04
	, FVC
	, Charge
	, P_FVC
	, CPS
	, P_CPS
	, P_FC4UG04
	, FullCost
	, P_FullCost
	, MinPrice
	, P_MinPrice
	, P_PriceOff
	, NetMar
	, FCShield
	, PckSur
	, valid
	, errorScore
	, DiesPrice_sim
	, SamplePrice
	, DiesFullCost
	, DiesPriceClientQuote
	, DiesTecLife
	, DiesCommLife
	, MonthSalesPrev
	, SalesPrevCost
	, DiesFinCost
	, ClientQuoteReven
	, ExtraDiscountDies
	, WSR01_sim
	, MSR01_sim
	, NetProd01_sim
	, NetProd04_sim
	, DSR_sim
	, NetMar_sim
	, FCShield_sim
	, MinPrice_sim
	, P_MinPrice_sim

FROM dbo.v_QuoteFull_Q AS qf
INNER JOIN dbo.ReportPrintTicket AS prt 
    ON  qf.QuoteType = dbo.f_prt_getParameter ( 'QuoteType', prt.Chiave , '&')
    AND qf.CodQuote  = dbo.f_prt_getParameter ( 'CodQuote' , prt.Chiave , '&')
    AND qf.QuoteRev  = dbo.f_prt_getParameter ( 'QuoteRev' , prt.Chiave +'&' , '&')
    AND prt.Ticket   = @Ticket


/* OLD VERSION 
WITH Cte AS   -- carico i lemmi dei campi che mi servono per la stampa
(
SELECT Lingua,
       'prt1_'+ Lemma AS Lemma,
       CASE WHEN @Lingua = 'LB' 
            THEN Lemma 
            ELSE Traduzione END 
        AS Traduzione     -- il lemma corrisponde ai campi
FROM Vocabolario
WHERE Lemma IN ( 'ClientName'
                    ,'CodClient'
                    ,'CodItem'
                    ,'ItemDescr'
                    ,'CodifProfilo'
                    ,'ClasseMerc'
                    ,'CodClientAssoc'
                    ,'ClientNameAssoc'
                    ,'CodItemGroup'
                    ,'UnitWeight'
                    ,'RawMat'
                    ,'RawMatCost'
                    ,'RawMatExtraCost'
                    ,'RawMatFullCost'
                    ,'RawMatCost'
                    ,'RawMatExtraCost'
                    ,'BatchQty'
                    ,'ProvvCost'
                    ,'CodInco','TipoDies'
                    ,'CodDiesGroup'
                    ,'DiamDies'
                    ,'DiesPrice'
                    ,'HoleNumDies'
                    ,'DiesExpLife'
                    ,'NumDiesInList'
                    ,'DiesEOLife'
                    ,'NumDiesExaust'
                    ,'CodPlant'
                    ,'HoleNumDies'
                    ,'KeyAMIL'
                    ,'KgTeo'
                    ,'WSR01'
                    ,'NumSMED'
                    ,'MSR01'
                    ,'NetProd01'
                    ,'CodPackag'
                    ,'NetProd04'
                    ,'QuotaMan'
                    ,'LivPackage'
                    ,'LivPackageDet'
                    ,'PkgDesc'
                    ,'PRMWeight'
                    ,'DSR'
                    ,'PWeight'
                    ,'PTare'
                    ,'FSR'
                    ,'RefCost01'
                    ,'SellCost01'
                    ,'EECost'
                    ,'GasCost'	
                    ,'DiesCost'	
                    ,'RefCost04'	
                    ,'SellCost04'
                    ,'PackCost'
                    ,'ProvvCost'
                    ,'TranspCost'
                    ,'VC4UG01'
                    ,'VC4UG04'
                    ,'SC4UG01'	
                    ,'FVC'
                    ,'P_FVC'
                    ,'CPS'
                    ,'P_CPS'
                    ,'FC4UG04'
                    ,'P_FC4UG04'
                    ,'FullCost'
                    ,'P_FullCost'
                    ,'MinPrice'
                    ,'P_MinPrice'
                    ,'Charge'
                    ,'PriceOff'
                    ,'P_PriceOff'
                    ,'NetMar'
                    ,'FCShield'
                    ,'PckSur'
                 )
), 
ctepvt AS (                     -- faccio pivot dei lemmi e loro traduzioni
        SELECT
            Lingua,
                prt1_BatchQty,
                prt1_Charge,
                prt1_ClasseMerc,
                prt1_ClientName,
                prt1_ClientNameAssoc,
                prt1_CodClient,
                prt1_CodClientAssoc,
                prt1_CodDiesGroup,
                prt1_CodifProfilo,
                prt1_CodInco,
                prt1_CodItem,
                prt1_CodItemGroup,
                prt1_CodPackag,
                prt1_CodPlant,
                prt1_CPS,
                prt1_DiamDies,
                prt1_DiesCost,
                prt1_DiesEOLife,
                prt1_DiesExpLife,
                prt1_DiesPrice,
                prt1_DSR,
                prt1_EECost,
                prt1_FC4UG04,
                prt1_FCShield,
                prt1_FSR,
                prt1_FullCost,
                prt1_FVC,
                prt1_GasCost,
                prt1_HoleNumDies,
                prt1_ItemDescr,
                prt1_KeyAMIL,
                prt1_KgTeo,
                prt1_LivPackage,
                prt1_LivPackageDet,
                prt1_MinPrice,
                prt1_MSR01,
                prt1_NetMar,
                prt1_NetProd01,
                prt1_NetProd04,
                prt1_NumDiesExaust,
                prt1_NumDiesInList,
                prt1_NumSMED,
                prt1_P_CPS,
                prt1_P_FC4UG04,
                prt1_P_FullCost,
                prt1_P_FVC,
                prt1_P_MinPrice,
                prt1_P_PriceOff,
                prt1_PackCost,
                prt1_PckSur,
                prt1_PkgDesc,
                prt1_PriceOff,
                prt1_PRMWeight,
                prt1_ProvvCost,
                prt1_PTare,
                prt1_PWeight,
                prt1_QuotaMan,
                prt1_RawMat,
                prt1_RawMatCost,
                prt1_RawMatExtraCost,
                prt1_RawMatFullCost,
                prt1_RefCost01,
                prt1_RefCost04,
                prt1_SC4UG01,
                prt1_SellCost01,
                prt1_SellCost04,
                prt1_TipoDies,
                prt1_TranspCost,
                prt1_UnitWeight,
                prt1_VC4UG01,
                prt1_VC4UG04,
                prt1_WSR01
    FROM ( SELECT * FROM cte 
           WHERE Lemma Like 'prt1%' ) AS tab      -- al momento non serve ma se mettiamo i lemmi separati con prt1_ in vocabolario
    PIVOT ( MIN ( Traduzione )                                      -- possiamo semplicemente sostituire la tab vocabolario alla cte
    FOR Lemma IN ( 
            prt1_BatchQty,
            prt1_Charge,
            prt1_ClasseMerc,
            prt1_ClientName,
            prt1_ClientNameAssoc,
            prt1_CodClient,
            prt1_CodClientAssoc,
            prt1_CodDiesGroup,
            prt1_CodifProfilo,
            prt1_CodInco,
            prt1_CodItem,
            prt1_CodItemGroup,
            prt1_CodPackag,
            prt1_CodPlant,
            prt1_CPS,
            prt1_DiamDies,
            prt1_DiesCost,
            prt1_DiesEOLife,
            prt1_DiesExpLife,
            prt1_DiesPrice,
            prt1_DSR,
            prt1_EECost,
            prt1_FC4UG04,
            prt1_FCShield,
            prt1_FSR,
            prt1_FullCost,
            prt1_FVC,
            prt1_GasCost,
            prt1_HoleNumDies,
            prt1_ItemDescr,
            prt1_KeyAMIL,
            prt1_KgTeo,
            prt1_LivPackage,
            prt1_LivPackageDet,
            prt1_MinPrice,
            prt1_MSR01,
            prt1_NetMar,
            prt1_NetProd01,
            prt1_NetProd04,
            prt1_NumDiesExaust,
            prt1_NumDiesInList,
            prt1_NumSMED,
            prt1_P_CPS,
            prt1_P_FC4UG04,
            prt1_P_FullCost,
            prt1_P_FVC,
            prt1_P_MinPrice,
            prt1_P_PriceOff,
            prt1_PackCost,
            prt1_PckSur,
            prt1_PkgDesc,
            prt1_PriceOff,
            prt1_PRMWeight,
            prt1_ProvvCost,
            prt1_PTare,
            prt1_PWeight,
            prt1_QuotaMan,
            prt1_RawMat,
            prt1_RawMatCost,
            prt1_RawMatExtraCost,
            prt1_RawMatFullCost,
            prt1_RefCost01,
            prt1_RefCost04,
            prt1_SC4UG01,
            prt1_SellCost01,
            prt1_SellCost04,
            prt1_TipoDies,
            prt1_TranspCost,
            prt1_UnitWeight,
            prt1_VC4UG01,
            prt1_VC4UG04,
            prt1_WSR01        ) ) AS pvt
)
SELECT 
       -- chiave
       Vers
      ,QuoteType
      ,CodQuote
      ,QuoteRev
      -- valori
      ,BatchQty
      ,Charge
      ,ClasseMerc
      ,ClientName
      ,ClientNameAssoc
      ,CodClient
      ,CodClientAssoc
      ,CodDiesGroup
      ,CodifProfilo
      ,CodInco
      ,CodItem
      ,CodItemGroup
      ,CodPackag
      ,CodPlant
      ,CPS
      ,DiamDies
      ,DiesCost
      ,DiesEOLife
      ,DiesExpLife
      ,DiesPrice
      ,DSR
      ,EECost
      ,FC4UG01
      ,FC4UG04
      ,FCShield
      ,FSR
      ,FullCost
      ,FVC
      ,GasCost
      ,HoleNumDies
      ,IdxQState
      ,ItemDescr
      ,KeyAM
      ,KeyAMIL
      ,KgTeo
      ,LivPackage
      ,LivPackageDett
      ,MinPrice
      ,MSR01
      ,NetMar
      ,NetProd01
      ,NetProd04
      ,Note
      ,NumDiesExaust
      ,NumDiesInList
      ,NumSMED
      ,OH4UG01
      ,P_CPS
      ,P_FC4UG04
      ,P_FullCost
      ,P_FVC
      ,P_MinPrice
      ,P_PriceOff
      ,PackCost
      ,PckSur
      ,PkgDesc
      ,PriceOff
      ,PRMWeight
      ,ProvvCost
      ,PTare
      ,PWeight
      ,QuotaMan
      ,RawMat
      ,RawMatCost
      ,RawMatExtraCost
      ,RawMatFullCost
      ,RefCost01
      ,RefCost04
      ,SC4UG01
      ,SellCost01
      ,SellCost04
      ,TipoDies
      ,TranspCost
      ,UnitWeight
      ,VC4UG01
      ,VC4UG04
      ,WSR01
      -- lemmi x traduzione etichette campi
      ,ctepvt.*
FROM dbo.v_QuoteFull_Q
INNER JOIN ctepvt 
-- ON ctepvt.Lingua = 'EN'   -- qui va messa la variabile della lingua di stampa
-- ON ctepvt.Lingua = @Lingua  -- 'EN'   -- qui va messa la variabile della lingua di stampa
ON ctepvt.Lingua = CASE WHEN @Lingua = 'LB'      -- se richiede le Label dei campi estraggo i lemmi in inglese
                    THEN 'EN' 
                    ELSE @Lingua 
             END
*/

END
GO
PRINT N'Creating [tmp].[importItemsRaw]...';


GO


-- =============================================
-- Author:		S.E. Locatelli
-- Create date: 2013.11.29
-- Description:	Procedura per import dati in tabella tmp da file csv
-- =============================================
CREATE PROCEDURE [tmp].[importItemsRaw]
(
	 @fileType NVARCHAR(50) = 'ItemsRaw'
)
AS
BEGIN
	SET NOCOUNT ON;

	-- per Giancarlo: rendere parametrico con esecuzione sql x poter inserire nei parametri il separatore ed il resto? http://www.sqlteam.com/article/using-bulk-insert-to-load-a-text-file
	
	IF @fileType = 'ItemsRaw'
		BEGIN
			-- svuoto tabella temp
			TRUNCATE TABLE tmp.ItemsRaw

			-- carico dati bulk!
			BULK INSERT tmp.ItemsRaw
			FROM 'e:\test\ItemsRaw.csv'
			WITH (FIELDTERMINATOR = ';', ROWTERMINATOR = '\n', FIRSTROW = 2, ERRORFILE = 'e:\test\errorItems.log')
			--WITH (FIELDTERMINATOR = ';', ROWTERMINATOR = '\n', FIRSTROW = 2, ERRORFILE = 'e:\test\errorItems.log', CODEPAGE = '1252')

           	SELECT COUNT(*)  as RecordsIn FROM tmp.ItemsRaw

		END

END
GO
PRINT N'Creating [tmp].[convertTranspCostRaw]...';


GO


-- =============================================
-- Author:		S.E. Locatelli
-- Create date: 2013.11.28
-- Description:	Procedura per conversioen e tipizzazione dati da tmp a ext x TranspCostRaw
-- =============================================
CREATE PROCEDURE [tmp].[convertTranspCostRaw]
(
	 @fileType NVARCHAR(50) = 'TranspCostRaw'
)
AS
BEGIN
	SET NOCOUNT ON;

	-- per Giancarlo: rendere parametrico con esecuzione sql x poter inserire nei parametri il separatore ed il resto? http://www.sqlteam.com/article/using-bulk-insert-to-load-a-text-file
	
	IF @fileType = 'TranspCostRaw'
		BEGIN
			-- svuoto tabella temp
			TRUNCATE TABLE ext.TranspCostRaw

			-- inserisco con cast valori...
			INSERT	ext.TranspCostRaw
            WITH (TABLOCK)
					(TranspZone, TranspCost) 
            SELECT
				   TranspZone,
                   MAX(CAST( CAST( REPLACE( '0' + TranspCost,',','.' )AS float )AS decimal( 18,9 )))  AS TranspCost
            FROM tmp.TranspCostRaw
			GROUP BY TranspZone

			SELECT COUNT(*)  as RecordsIn FROM ext.TranspCostRaw
		END

END
GO
PRINT N'Creating [tmp].[importDiesGroupRaw]...';


GO


-- =============================================
-- Author:		S.E. Locatelli
-- Create date: 2013.12.02
-- Description:	Procedura per import dati in tabella tmp da file csv
-- =============================================
CREATE PROCEDURE [tmp].[importDiesGroupRaw]
(
	 @fileType NVARCHAR(50) = 'DiesGroupRaw'
)
AS
BEGIN
	SET NOCOUNT ON;

	-- per Giancarlo: rendere parametrico con esecuzione sql x poter inserire nei parametri il separatore ed il resto? http://www.sqlteam.com/article/using-bulk-insert-to-load-a-text-file
	
	IF @fileType = 'DiesGroupRaw'
		BEGIN
			-- svuoto tabella temp
			TRUNCATE TABLE tmp.DiesGroupRaw

			-- carico dati bulk!
			BULK INSERT tmp.DiesGroupRaw
			FROM 'e:\test\DiesGroupRaw.csv'
			WITH (FIELDTERMINATOR = ';', ROWTERMINATOR = '\n', FIRSTROW = 2, ERRORFILE = 'e:\test\errorDiesGroup.log')
			--WITH (FIELDTERMINATOR = ';', ROWTERMINATOR = '\n', FIRSTROW = 2, ERRORFILE = 'e:\test\errorDiesGroup.log', CODEPAGE = '1252')

           	SELECT COUNT(*)  as RecordsIn FROM tmp.DiesGroupRaw

		END

END
GO
PRINT N'Creating [tmp].[importTranspCostRaw]...';


GO


-- =============================================
-- Author:		S.E. Locatelli
-- Create date: 2014.01.16
-- Description:	Procedura per import dati in tabella tmp da file csv
-- =============================================
create PROCEDURE [tmp].[importTranspCostRaw]
(
	 @fileType NVARCHAR(50) = 'TranspCostRaw'
)
AS
BEGIN
	SET NOCOUNT ON;

	-- per Giancarlo: rendere parametrico con esecuzione sql x poter inserire nei parametri il separatore ed il resto? http://www.sqlteam.com/article/using-bulk-insert-to-load-a-text-file
	
	IF @fileType = 'TranspCostRaw'
		BEGIN
			-- svuoto tabella temp
			TRUNCATE TABLE tmp.TranspCostRaw

			-- carico dati bulk!
			BULK INSERT tmp.TranspCostRaw
			FROM 'e:\test\TranspCostRaw.csv'
			WITH (FIELDTERMINATOR = ';', ROWTERMINATOR = '\n', FIRSTROW = 2, ERRORFILE = 'e:\test\errorTranspCost.log')
			--WITH (FIELDTERMINATOR = ';', ROWTERMINATOR = '\n', FIRSTROW = 2, ERRORFILE = 'e:\test\errorTranspCost.log', CODEPAGE = '1252')

           	SELECT COUNT(*)  as RecordsIn FROM tmp.TranspCostRaw

		END

END
GO
PRINT N'Creating [tmp].[convertDiesRaw]...';


GO


-- =============================================
-- Author:		S.E. Locatelli
-- Create date: 2013.12.02
-- Description:	Procedura per conversione e tipizzazione dati da tmp a ext x DiesRaw
-- =============================================
CREATE PROCEDURE [tmp].[convertDiesRaw]
(
	 @fileType NVARCHAR(50) = 'DiesRaw'
)
AS
BEGIN
	SET NOCOUNT ON;

	-- per Giancarlo: rendere parametrico con esecuzione sql x poter inserire nei parametri il separatore ed il resto? http://www.sqlteam.com/article/using-bulk-insert-to-load-a-text-file
	
	IF @fileType = 'DiesRaw'
		BEGIN
			-- svuoto tabella temp
			TRUNCATE TABLE ext.DiesRaw

			-- inserisco con cast valori...
			INSERT ext.DiesRaw
            WITH (TABLOCK)
            ( CodDies, HoleNum, CodItem, CodDiesGroup, Price, ExpLife, ActLife, Active ) 
            SELECT
                   CodDies,
                   CAST(ISNULL(HoleNum,0) AS INT) AS HoleNum,
				   CodItem,
				   CodDiesGroup,
                   CAST( CAST( REPLACE( '0' + Price,',','.' )AS float )AS decimal( 9,3 ))  AS Price,
                   CAST( CAST( REPLACE( '0' + ExpLife,',','.' )AS float )AS decimal( 9,2 ))  AS ExpLife,
                   CAST( CAST( REPLACE( '0' + ActLife,',','.' )AS float )AS decimal( 9,2 ))  AS ActLife,
                   CAST(ISNULL(Active,0) AS INT) AS Active
            FROM tmp.DiesRaw;

			SELECT COUNT(*)  as RecordsIn FROM ext.DiesRaw
		END

END
GO
PRINT N'Creating [tmp].[convertClientsRaw]...';


GO


-- =============================================
-- Author:		S.E. Locatelli
-- Create date: 2013.11.28
-- Description:	Procedura per conversioen e tipizzazione dati da tmp a ext x ClientsRaw
-- =============================================
CREATE PROCEDURE [tmp].[convertClientsRaw]
(
	 @fileType NVARCHAR(50) = 'ClientsRaw'
)
AS
BEGIN
	SET NOCOUNT ON;

	-- per Giancarlo: rendere parametrico con esecuzione sql x poter inserire nei parametri il separatore ed il resto? http://www.sqlteam.com/article/using-bulk-insert-to-load-a-text-file
	
	IF @fileType = 'ClientsRaw'
		BEGIN
			-- svuoto tabella temp
			TRUNCATE TABLE ext.ClientsRaw

			-- inserisco con cast valori...
			INSERT ext.ClientsRaw
            WITH (TABLOCK)
            ( CodClient, ClientName, CodAg, ZipCode, City, [State], Nation, TranspZone) 
            SELECT
                   CodClient,
                   ClientName,
                   CodAg,
                   ZipCode,
                   City,
				   [State],
				   Nation,
				   TranspZone
            FROM tmp.ClientsRaw;

			SELECT COUNT(*)  as RecordsIn FROM ext.ClientsRaw
		END

END
GO
PRINT N'Creating [tmp].[importDiesRaw]...';


GO


-- =============================================
-- Author:		S.E. Locatelli
-- Create date: 2013.12.02
-- Description:	Procedura per import dati in tabella tmp da file csv
-- =============================================
create PROCEDURE [tmp].[importDiesRaw]
(
	 @fileType NVARCHAR(50) = 'DiesRaw'
)
AS
BEGIN
	SET NOCOUNT ON;

	-- per Giancarlo: rendere parametrico con esecuzione sql x poter inserire nei parametri il separatore ed il resto? http://www.sqlteam.com/article/using-bulk-insert-to-load-a-text-file
	
	IF @fileType = 'DiesRaw'
		BEGIN
			-- svuoto tabella temp
			TRUNCATE TABLE tmp.DiesRaw

			-- carico dati bulk!
			BULK INSERT tmp.DiesRaw
			FROM 'e:\test\DiesRaw.csv'
			WITH (FIELDTERMINATOR = ';', ROWTERMINATOR = '\n', FIRSTROW = 2, ERRORFILE = 'e:\test\errorDies.log')
			--WITH (FIELDTERMINATOR = ';', ROWTERMINATOR = '\n', FIRSTROW = 2, ERRORFILE = 'e:\test\errorDies.log', CODEPAGE = '1252')

           	SELECT COUNT(*)  as RecordsIn FROM tmp.DiesRaw

		END

END
GO
PRINT N'Creating [tmp].[convertItemsRaw]...';


GO


-- =============================================
-- Author:		S.E. Locatelli
-- Create date: 2013.11.28
-- Description:	Procedura per conversioen e tipizzazione dati da tmp a ext x ItemsRaw
-- =============================================
CREATE PROCEDURE [tmp].[convertItemsRaw]
(
	 @fileType NVARCHAR(50) = 'ItemsRaw'
)
AS
BEGIN
	SET NOCOUNT ON;

	-- per Giancarlo: rendere parametrico con esecuzione sql x poter inserire nei parametri il separatore ed il resto? http://www.sqlteam.com/article/using-bulk-insert-to-load-a-text-file
	
	IF @fileType = 'ItemsRaw'
		BEGIN
			-- svuoto tabella temp
			TRUNCATE TABLE ext.ItemsRaw

			-- inserisco con cast valori...
			INSERT ext.ItemsRaw
            WITH (TABLOCK)
            ( CodItem, ItemDescr, UnitWeight, CodPlant, CodItemGroup, Class01, Class02, Class03, Class04, Class05 ) 
            SELECT	DISTINCT
                   CodItem,
                   ItemDescr,
                   CAST( CAST( REPLACE( '0' + UnitWeight,',','.' )AS float )AS decimal( 9,3 ))  AS UnitWeight,
				   CodPlant, 
				   CodItemGroup,
                   Class01, 
				   Class02, 
				   Class03, 
				   Class04, 
				   Class05
            FROM tmp.ItemsRaw;

			SELECT COUNT(*)  as RecordsIn FROM ext.ItemsRaw
		END

END
GO
PRINT N'Creating [tmp].[convertDiesGroupRaw]...';


GO



-- =============================================
-- Author:		S.E. Locatelli
-- Create date: 2014.01.08
-- Description:	Procedura per conversione e tipizzazione dati da tmp a ext x DiesGroupRaw
-- =============================================
CREATE PROCEDURE [tmp].[convertDiesGroupRaw]
(
	 @fileType NVARCHAR(50) = 'DiesGroupRaw'
)
AS
BEGIN
	SET NOCOUNT ON;

	-- per Giancarlo: rendere parametrico con esecuzione sql x poter inserire nei parametri il separatore ed il resto? http://www.sqlteam.com/article/using-bulk-insert-to-load-a-text-file
	
	IF @fileType = 'DiesGroupRaw'
		BEGIN
			-- svuoto tabella temp
			TRUNCATE TABLE ext.DiesGroupRaw

			-- inserisco con cast valori...
			INSERT ext.DiesGroupRaw
            WITH (TABLOCK)
            ( CodDiesGroup, Price, QtyTot, QtyEOL, ExpLife, EOLLife) 
            SELECT
                   CodDiesGroup,
				   CAST( CAST( REPLACE( '0' + REPLACE(Price,'.',''),',','.' ) AS float )AS decimal( 9,3 ))  AS Price,
				   CAST(ISNULL(QtyTot,0) AS INT) AS QtyTot,
				   CAST(ISNULL(QtyEOL,0) AS INT) AS QtyEOL,
                   CAST( CAST( REPLACE( '0' + REPLACE(ExpLife,'.',''),',','.' ) AS float )AS decimal( 9,2 ))  AS ExpLife,
                   CAST( CAST( REPLACE( '0' + REPLACE(EOLLife,'.',''),',','.' ) AS float )AS decimal( 9,2 ))  AS EOLLife
            FROM tmp.DiesGroupRaw;

			SELECT COUNT(*)  as RecordsIn FROM ext.DiesGroupRaw
		END

END
GO
PRINT N'Creating [tmp].[convertPackagRaw]...';


GO


-- =============================================
-- Author:		S.E. Locatelli
-- Create date: 2013.11.29
-- Description:	Procedura per conversioen e tipizzazione dati da tmp a ext x PackagRaw
-- =============================================
CREATE PROCEDURE [tmp].[convertPackagRaw]
(
	 @fileType NVARCHAR(50) = 'PackagRaw'
)
AS
BEGIN
	SET NOCOUNT ON;

	-- per Giancarlo: rendere parametrico con esecuzione sql x poter inserire nei parametri il separatore ed il resto? http://www.sqlteam.com/article/using-bulk-insert-to-load-a-text-file
	
	IF @fileType = 'PackagRaw'
		BEGIN
			-- svuoto tabella temp
			TRUNCATE TABLE ext.PackagRaw

			-- inserisco con cast valori...
			INSERT ext.PackagRaw
            WITH (TABLOCK)
            ( CodPackag, PackagDesc, RMCost, RMWeight, Tare, FullWeight ) 
            SELECT
                   CodPackag,
				   PackagDesc,
                   CAST( CAST( REPLACE( '0' + RMCost,',','.' )AS float )AS decimal( 9,3 ))  AS RMCost,
                   CAST( CAST( REPLACE( '0' + RMWeight,',','.' )AS float )AS decimal( 9,4 ))  AS RMWeight,
                   CAST( CAST( REPLACE( '0' + Tare,',','.' )AS float )AS decimal( 9,4 ))  AS Tare,
                   CAST( CAST( REPLACE( '0' + FullWeight,',','.' )AS float )AS decimal( 9,4 ))  AS FullWeight
            FROM tmp.PackagRaw;

			SELECT COUNT(*)  as RecordsIn FROM ext.PackagRaw
		END

END
GO
PRINT N'Creating [tmp].[importPackagRaw]...';


GO


-- =============================================
-- Author:		S.E. Locatelli
-- Create date: 2013.11.29
-- Description:	Procedura per import dati in tabella tmp da file csv
-- =============================================
create PROCEDURE [tmp].[importPackagRaw]
(
	 @fileType NVARCHAR(50) = 'PackagRaw'
)
AS
BEGIN
	SET NOCOUNT ON;

	-- per Giancarlo: rendere parametrico con esecuzione sql x poter inserire nei parametri il separatore ed il resto? http://www.sqlteam.com/article/using-bulk-insert-to-load-a-text-file
	
	IF @fileType = 'PackagRaw'
		BEGIN
			-- svuoto tabella temp
			TRUNCATE TABLE tmp.PackagRaw

			-- carico dati bulk!
			BULK INSERT tmp.PackagRaw
			FROM 'e:\test\PackagRaw.csv'
			WITH (FIELDTERMINATOR = ';', ROWTERMINATOR = '\n', FIRSTROW = 2, ERRORFILE = 'e:\test\errorPackag.log')
			--WITH (FIELDTERMINATOR = ';', ROWTERMINATOR = '\n', FIRSTROW = 2, ERRORFILE = 'e:\test\errorPackag.log', CODEPAGE = '1252')

           	SELECT COUNT(*)  as RecordsIn FROM tmp.PackagRaw

		END

END
GO
PRINT N'Creating [tmp].[convertProductionLogRaw]...';


GO



-- =============================================
-- Author:		S.E. Locatelli
-- Create date: 2013.11.28
-- Description:	Procedura per conversioen e tipizzazione dati da tmp a ext x ProductionLogRaw
-- =============================================
CREATE PROCEDURE [tmp].[convertProductionLogRaw]
(
	 @fileType NVARCHAR(50) = 'ProductionLogRaw'
)
AS
BEGIN
	SET NOCOUNT ON;

	-- per Giancarlo: rendere parametrico con esecuzione sql x poter inserire nei parametri il separatore ed il resto? http://www.sqlteam.com/article/using-bulk-insert-to-load-a-text-file
	
	IF @fileType = 'ProductionLogRaw'
		BEGIN
			-- svuoto tabella temp
			TRUNCATE TABLE ext.ProductionLogRaw

			-- inserisco con cast valori...
			INSERT ext.ProductionLogRaw
            WITH (TABLOCK)
            ( EventStart, EventEnd, CodPlant, ProcessNum, NrPos, CodDies, CodClient, OrderNum, BatchNum, ProcessType, EventType, RawMat, CodPackag, QtyIN, QtyOUT, QtyEXT, NumIN, NumOUT, QuotaPlant, QuotaMan, Tags, okPr, okQM, okSc, okDi )

            SELECT
                   dbo.f_dtFromRaw( EventStart ) AS EventStart,  -- record nulli sono già stati cancellati
                   dbo.f_dtFromRaw( EventEnd )   AS EventEnd,    -- record nulli sono già stati cancellati
                   dbo.f_trim(ISNULL(CodPlant   ,'')),
                   dbo.f_trim(ISNULL(ProcessNum ,'')),
                   dbo.f_trim(ISNULL(NrPos      ,'')),
                   dbo.f_trim(ISNULL(CodDies    ,'')),
                   dbo.f_trim(ISNULL(CodClient  ,'')),
                   dbo.f_trim(ISNULL(OrderNum   ,'')),
                   dbo.f_trim(ISNULL(BatchNum   ,'')),
                   dbo.f_trim(ISNULL(ProcessType,'')),
                   dbo.f_trim(ISNULL(EventType  ,'')),
                   dbo.f_trim(ISNULL(RawMat     ,'')),
                   dbo.f_trim(ISNULL(CodPackag  ,'')),
                   CAST( CAST( REPLACE( '0' + ISNULL(QtyIN,'') ,',','.' ) AS float )  AS decimal( 18,4 ))  AS QtyIN,
                   CAST( CAST( REPLACE( '0' + ISNULL(QtyOUT,''),',','.' ) AS float ) AS decimal( 18,4 ))   AS QtyOUT,
                   CAST( CAST( REPLACE( '0' + ISNULL(QtyEXT,''),',','.' ) AS float ) AS decimal( 18,4 ))   AS QtyEXT,
                   CAST( ISNULL(NumIN   ,'') AS int )AS NumIN,
                   CAST( ISNULL(NumOUT  ,'') AS int )AS NumOUT,
                   CAST( CAST( REPLACE( '0' + ISNULL(QuotaPlant,''),',','.' ) AS float )AS decimal( 9,4 )) AS QuotaPlant,
                   CAST( CAST( REPLACE( '0' + ISNULL(QuotaMan,''),',','.' )   AS float )AS decimal( 9,4 )) AS QuotaMan,
                   dbo.f_trim(ISNULL(Tags  ,'')),
				   okPr,
				   okQM,
				   okSc,
				   okDi
            FROM tmp.ProductionLogRaw;

			SELECT COUNT(*)  as RecordsIn FROM ext.ProductionLogRaw
		END

END
GO
PRINT N'Creating [tmp].[importProductionLogRaw]...';


GO




-- =============================================
-- Author:		S.E. Locatelli
-- Create date: 2013.11.28
-- Description:	Procedura per import dati in tabelal tmp da file csv
-- 
-- TRUNCATE TABLE tmp.ProductionLogRaw_KO
--
-- =============================================
CREATE PROCEDURE [tmp].[importProductionLogRaw]
(
	 @fileType NVARCHAR(50) = 'ProductionLogRaw'
)
AS
BEGIN
	SET NOCOUNT ON;

	-- per Giancarlo: rendere parametrico con esecuzione sql x poter inserire nei parametri il separatore ed il resto? http://www.sqlteam.com/article/using-bulk-insert-to-load-a-text-file
	
	IF @fileType = 'ProductionLogRaw'
		BEGIN
			-- svuoto tabella temp
			TRUNCATE TABLE tmp.ProductionLogRaw

			-- carico dati bulk!
			BULK INSERT tmp.ProductionLogRaw
			FROM 'e:\test\ProductRaw.csv'
			
			WITH (FIELDTERMINATOR = ';', ROWTERMINATOR = '\n', FIRSTROW = 2, ERRORFILE = 'e:\test\errorProduct.log')
			--WITH (FIELDTERMINATOR = ';', ROWTERMINATOR = '\n', FIRSTROW = 2, ERRORFILE = 'e:\test\errorProduct.log', CODEPAGE = '1252')

            -- ===============================================================================
            -- pulisco l tabella dai record con chiave duplicata ( se doppi li elimino tutti )
            -- ===============================================================================
            SET XACT_ABORT ON;
            BEGIN TRAN 

                -- salvo i dati con chiave duplicata
                INSERT INTO tmp.ProductionLogRaw_KO
                SELECT Prod.*, GETDATE() FROM tmp.ProductionLogRaw AS Prod
                INNER JOIN 
                            (
                            SELECT EventStart, EventEnd, CodPlant, ProcessNum, NrPos, CodDies
                            FROM tmp.ProductionLogRaw
                            GROUP BY  EventStart, EventEnd, CodPlant, ProcessNum, NrPos, CodDies
                            HAVING COUNT(*)>1
                            ) AS Dupl ON    Prod.EventStart  = Dupl.EventStart AND
                                            Prod.EventEnd    = Dupl.EventEnd AND
                                            Prod.CodPlant    = Dupl.CodPlant AND
                                            Prod.ProcessNum  = Dupl.ProcessNum AND
                                            Prod.NrPos       = Dupl.NrPos  AND
                                            Prod.CodDies     = Dupl.CodDies

                -- Cancello i record con chiave duplicata
                DELETE Prod
                WITH (TABLOCK)
                FROM tmp.ProductionLogRaw AS Prod
                INNER JOIN 
                            (
                            SELECT EventStart, EventEnd, CodPlant, ProcessNum, NrPos, CodDies
                            FROM tmp.ProductionLogRaw
                            GROUP BY  EventStart, EventEnd, CodPlant, ProcessNum, NrPos, CodDies
                            HAVING COUNT(*)>1
                            ) AS Dupl ON    Prod.EventStart  = Dupl.EventStart AND
                                            Prod.EventEnd    = Dupl.EventEnd AND
                                            Prod.CodPlant    = Dupl.CodPlant AND
                                            Prod.ProcessNum  = Dupl.ProcessNum AND
                                            Prod.NrPos       = Dupl.NrPos  AND
                                            Prod.CodDies     = Dupl.CodDies

            -- ===============================================================================
            -- pulisco la tabella dai record con date non corrette
            -- ===============================================================================
            DELETE FROM tmp.ProductionLogRaw
            WITH (TABLOCK)
            OUTPUT deleted.* INTO tmp.ProductionLogRaw_KO    -- salvo i record cancellati in tabella KO
                   ( EventStart, EventEnd, CodPlant, ProcessNum, NrPos, CodDies, CodClient, OrderNum, BatchNum, ProcessType, EventType, RawMat
                   , CodPackag, QtyIN, QtyOUT, QtyEXT, NumIN, NumOUT, QuotaPlant, QuotaMan, Tags, okPr, okQM, okSc, okDi )
            WHERE EventStart >= EventEnd
                  OR CONVERT( BIGINT , EventStart ) + 68000000000000 <= EventEnd   -- record che darebbero errore poi nel datediff > 68 anni
                  OR EventStart IS NULL
                  OR EventEnd   IS NULL

--            SELECT * FROM tmp.ProductionLogRaw_KO

            --ROLLBACK
            COMMIT

			SELECT COUNT(*) AS RecordsIn FROM tmp.ProductionLogRaw

		END
END
GO
PRINT N'Creating [tmp].[importClientsRaw]...';


GO



-- =============================================
-- Author:		S.E. Locatelli
-- Mod. date: 2013.11.29
-- Description:	Procedura per import dati in tabella tmp da file csv
-- =============================================
CREATE PROCEDURE [tmp].[importClientsRaw]
(
	 @fileType NVARCHAR(50) = 'ClientsRaw'
)
AS
BEGIN
	SET NOCOUNT ON;

	-- per Giancarlo: rendere parametrico con esecuzione sql x poter inserire nei parametri il separatore ed il resto? http://www.sqlteam.com/article/using-bulk-insert-to-load-a-text-file
	
	IF @fileType = 'ClientsRaw'
		BEGIN
			-- svuoto tabella temp
			TRUNCATE TABLE tmp.ClientsRaw

			-- carico dati bulk!
			BULK INSERT tmp.ClientsRaw
			FROM 'e:\test\ClientsRaw.csv'
			WITH (FIELDTERMINATOR = ';', ROWTERMINATOR = '\n', FIRSTROW = 2, ERRORFILE = 'e:\test\errorClients.log')
			--WITH (FIELDTERMINATOR = ';', ROWTERMINATOR = '\n', FIRSTROW = 2, ERRORFILE = 'e:\test\errorClients.log', CODEPAGE = '1252')

           	SELECT COUNT(*)  as RecordsIn FROM tmp.ClientsRaw

		END

END
GO
PRINT N'Creating [tmp].[convertOrdersHistRaw]...';


GO
-- =============================================
-- Author:		Steamware
-- Mod. date: 2014.05.22
-- Description:	Procedura per conversione e tipizzazione dati da tmp a ext x OrdersHistRaw
-- =============================================
CREATE PROCEDURE [tmp].[convertOrdersHistRaw]
(
     @fileType NVARCHAR(50) = 'OrdersHistRaw'
)
AS
BEGIN
    SET NOCOUNT ON;

    -- per Giancarlo: rendere parametrico con esecuzione sql x poter inserire nei parametri il separatore ed il resto? http://www.sqlteam.com/article/using-bulk-insert-to-load-a-text-file
    
    IF @fileType = 'OrdersHistRaw'
        BEGIN
            -- svuoto tabella temp
            TRUNCATE TABLE ext.OrdersHistRaw

            -- inserisco con cast valori...
            INSERT ext.OrdersHistRaw
            WITH (TABLOCK)
            ( OrdNum, OrdRow, OrdDate, CodClient, CodItem, RawMat, RawMatCost, BatchQty, CodInco, OrdPrice, RawMatExtraCost, PriceOff, OrdQty, ProvvCost) 
            SELECT
                    OrdNum,
                    OrdRow,
                    dbo.f_dtFromRaw( OrdDate ) AS OrdDate,
                    CodClient,
                    CodItem, 
                    RawMat, 
                    CONVERT( DECIMAL( 18,6 ), CONVERT ( FLOAT , REPLACE( '0' + REPLACE(RawMatCost,'.',''),',','.' ) ))      AS RawMatCost,
                    CONVERT(INT, CONVERT ( FLOAT , REPLACE( '0' + REPLACE(BatchQty,'.',''),',','.' ) ))                     AS BatchQty,         -- lotto
                    CodInco, 
                    CONVERT( DECIMAL( 18,6 ), CONVERT ( FLOAT , REPLACE( '0' + REPLACE(OrdPrice,'.',''),',','.' ) ))        AS OrdPrice,
                    CONVERT( DECIMAL( 18,6 ), CONVERT ( FLOAT , REPLACE( '0' + REPLACE(RawMatExtraCost,'.',''),',','.' ) )) AS RawMatExtraCost,
                    CONVERT( DECIMAL( 9,6 ),  CONVERT ( FLOAT , REPLACE( '0' + REPLACE(PriceOff,'.',''),',','.' ) ))        AS PriceOff,         -- trasformazione
                    CONVERT( INT,             CONVERT ( FLOAT , REPLACE( '0' + REPLACE(OrdQty,'.',''),',','.' ) ))          AS OrdQty,
                    CONVERT( DECIMAL( 9,6 ),  CONVERT ( FLOAT , REPLACE( '0' + REPLACE(ProvvCost,'.',''),',','.' ) ))       AS ProvvCost         -- provvigioni
            FROM tmp.OrdersHistRaw;

            SELECT COUNT(*)  as RecordsIn FROM ext.OrdersHistRaw
        END

END
GO
PRINT N'Creating [tmp].[importOrdersHistRaw]...';


GO
-- =============================================
-- Author:		S.E. Locatelli
-- mod. date: 2014.05.22
-- Description:	Procedura per import dati in tabella tmp da file csv
-- 
-- TRUNCATE TABLE [tmp].[OrdersHistRaw]
--
-- =============================================
CREATE PROCEDURE [tmp].[importOrdersHistRaw]
(
	 @fileType NVARCHAR(50) = 'OrdersHistRaw'
)
AS
BEGIN
	SET NOCOUNT ON;

	-- per Giancarlo: rendere parametrico con esecuzione sql x poter inserire nei parametri il separatore ed il resto? http://www.sqlteam.com/article/using-bulk-insert-to-load-a-text-file
	
	IF @fileType = 'OrdersHistRaw'
		BEGIN
			-- svuoto tabella temp
			TRUNCATE TABLE tmp.OrdersHistRaw

			-- carico dati bulk!
			BULK INSERT tmp.OrdersHistRaw
			FROM 'e:\test\MarginRep_Import.csv'
			WITH (FIELDTERMINATOR = ';', ROWTERMINATOR = '\n', FIRSTROW = 2, ERRORFILE = 'e:\test\errorOrdersHist.log')
			--WITH (FIELDTERMINATOR = ';', ROWTERMINATOR = '\n', FIRSTROW = 2, ERRORFILE = 'e:\test\errorProduct.log', CODEPAGE = '1252')

			SELECT COUNT(*) AS RecordsIn FROM tmp.OrdersHistRaw
		END
END
GO
PRINT N'Creating [voc].[stp_insNewLemma]...';


GO
/*************************************
* STORED PROCEDURE stp_insNewLemma
*
*  inseriemtno lemma vocabolario
*
* mod : 14/05/2012	
* aut : S.E. Locatelli
**************************************/
CREATE PROCEDURE [voc].[stp_insNewLemma]
(
    @lemma		NVARCHAR(50),
    @traduzione NVARCHAR(500),
    @OverWrite  CHAR(1) = 'Y'    -- Y/N Per forzarne inserimento anche se già presente
)
AS

-- elimino se c'era già e se richiesto...
IF @OverWrite = 'Y'
BEGIN 
    DELETE FROM	Vocabolario
    WHERE lemma = @lemma
END

-- inserisco x tutte le lingue attive...
INSERT INTO	Vocabolario
SELECT		lingua, @lemma, @traduzione 
FROM		Lingue

SELECT		*
FROM		Vocabolario
WHERE		lemma = @lemma

RETURN
GO
PRINT N'Creating [voc].[stp_getByLingua]...';


GO

CREATE PROCEDURE [voc].[stp_getByLingua]
(
	@Lingua nvarchar(3)
)
AS
	SET NOCOUNT ON;
SELECT        Lingua, Lemma, Traduzione
FROM            Vocabolario
WHERE        (Lingua = @Lingua)
GO
PRINT N'Creating [voc].[stp_getByLinguaLemmaLike]...';


GO


/*************************************
* STORED PROCEDURE stp_getByLemmaLike
*
*  elenco record da ricerca LIKE su lemma
*
* mod : 2014.04.28
* aut : S.E. Locatelli
**************************************/
CREATE PROCEDURE [voc].[stp_getByLinguaLemmaLike]
(
	@Lingua NVARCHAR(3),
	@search NVARCHAR(50)
)
AS

SET NOCOUNT ON;
SELECT   Lingua, Lemma
        ,CASE WHEN @Lingua = 'LB' THEN CONVERT(NVARCHAR(500),Lemma) 
                                  ELSE Traduzione END 
         AS Traduzione          -- la traduzione corrisponde ai campi/lemmi x i report
FROM	Vocabolario
WHERE   (Lemma LIKE @search + '%')
        AND ( Lingua =  CASE WHEN @Lingua = 'LB'      -- se richiede le Label dei campi estraggo i lemmi in inglese
                            THEN 'EN' 
                            ELSE @Lingua 
                        END )

/* OLD
SELECT  Lingua, Lemma, Traduzione
FROM	Vocabolario
WHERE   (Lemma LIKE @search + '%')
	AND	(Lingua = @Lingua)
*/
GO
PRINT N'Creating [voc].[stp_updateQuery]...';


GO

CREATE PROCEDURE [voc].[stp_updateQuery]
(
	@Traduzione nvarchar(500),
	@Original_Lingua nvarchar(3),
	@Original_Lemma nvarchar(50)
)
AS
	SET NOCOUNT OFF;
UPDATE [dbo].[Vocabolario] SET [Traduzione] = @Traduzione WHERE ([Lingua] = @Original_Lingua) AND ([Lemma] = @Original_Lemma)
GO
PRINT N'Creating [voc].[stp_upsertLemma]...';


GO
/*************************************
* STORED PROCEDURE stp_upsertLemma
*
*  upsert record lemma
*
* mod : 14/05/2012	
* aut : S.E. Locatelli
**************************************/
create PROCEDURE [voc].[stp_upsertLemma]
(
	@Lingua		NVARCHAR(3),
    @Lemma		NVARCHAR(50),
    @Traduzione NVARCHAR(500)
)
AS

-- effettuo merge x upsert!

 MERGE Vocabolario AS target
    USING (SELECT @Lingua, @Lemma, @Traduzione) AS source (Lingua, Lemma, Traduzione)
    ON (target.Lingua = source.Lingua AND target.Lemma = source.Lemma)
    WHEN MATCHED THEN 
        UPDATE SET Traduzione = source.traduzione
	WHEN NOT MATCHED THEN	
	    INSERT (Lingua, Lemma, Traduzione)
	    VALUES (source.Lingua, source.Lemma, source.Traduzione);

RETURN
GO
PRINT N'Creating [voc].[stp_voUpdateLemmiReport]...';


GO
-- =============================================
-- Author:		Samuele Locatelli
-- Create date: 2014.05.09
-- Description:	riallinea le traduzioni dei report ai termini corrispondenti a video
-- =============================================
CREATE PROCEDURE voc.stp_voUpdateLemmiReport
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- mostro situazione iniziale
    SELECT *
    FROM Vocabolario v1
    inner join vocabolario v ON replace(v1.Lemma, 'C2P_prt1_','') = v.Lemma AND v1.Lingua = v.Lingua
    WHERE v1.lemma LIKE 'C2P_prt1_%'

    -- update!
    UPDATE  v1
    SET     traduzione = v.traduzione
    FROM    Vocabolario v1
        INNER JOIN vocabolario v ON replace(v1.Lemma, 'C2P_prt1_','') = v.Lemma AND v1.Lingua = v.Lingua
    WHERE   v1.lemma LIKE 'C2P_prt1_%'


    -- mostro situazione finale
    SELECT *
    FROM Vocabolario v1
    inner join vocabolario v ON replace(v1.Lemma, 'C2P_prt1_','') = v.Lemma AND v1.Lingua = v.Lingua 
    WHERE v1.lemma LIKE 'C2P_prt1_%'

END
GO
PRINT N'Creating [ext].[stp_mergePackage2ItemClient]...';


GO



-- =============================================
-- Author:		S.E. Locatelli
-- Create date: 2013.11.27
-- Description:	Procedura per import dati in Package2ItemClient da dati ProductionLogRaw
-- =============================================
CREATE PROCEDURE [ext].[stp_mergePackage2ItemClient]
(
	@source NVARCHAR(20) = 'ProductionLog', -- nome della tabella sorgente tra ProductionLogRaw e ItemsRaw
	@dateFrom	DATETIME, -- data da cui iniziare a caricare
	@dateTo		DATETIME  -- data fino a cui caricare
)
AS
BEGIN
	SET NOCOUNT ON;
	

	-- Create a temporary table variable to hold the output actions.
	DECLARE @SummaryOfChanges TABLE(Change VARCHAR(20));
	
    -- import con MERGE... verifico tipo di caricamento richiesto!
	IF @source = 'ProductionLog' -- carico da tracciato produzione
		BEGIN
			MERGE INTO Package2ItemClient AS Target
			USING	(
					--SELECT		dd.CodItem, plr.CodClient, plr.CodPackag, SUM(QtyOUT) AS TotQta, COUNT(*) AS NumEv
					--		  , SUM(QtyOUT) / COUNT(*) AS PesoMedio
					--		  , SUM(QtyEXT) / COUNT(*) AS TaraMedia
					--FROM		ext.ProductionLogRaw plr
					--			INNER JOIN DiesDet dd ON plr.CodDies = dd.CodDies
					--			WHERE ISNULL(plr.CodPackag, '') <> ''
					--GROUP BY	dd.CodItem, plr.CodClient, plr.CodPackag 
                    SELECT	
                             dd.CodItem
                           , pl.CodClient
                           , pl.CodPackag
                           , SUM(QtyOUT) AS TotQta
                    --       , COUNT(*) AS NumEv
                           , SUM(QtyOUT) / COUNT(*) AS PesoMedio
                           , SUM(QtyEXT) / COUNT(*) AS TaraMedia
                           -- dati produttività imballo
                           , ROUND(SUM(QtyOUT* QuotaMan) / CASE WHEN SUM(QtyOUT) = 0 THEN 1 ELSE SUM(QtyOUT) END,0) as NumImb
                           , SUM(Duration) AS Durata
                    FROM	dbo.ProductionLog pl 
                    INNER JOIN dbo.DiesDet dd ON pl.CodDies=dd.CodDies

                    WHERE	pl.ProcessNum = '04'
                        AND pl.okPr = 1 AND pl.okQM = 1
                        AND ISNULL(pl.CodPackag, '') <> ''
                        AND	pl.EventStart BETWEEN @dateFrom AND @dateTo
                    GROUP BY dd.CodItem, pl.CodClient, pl.CodPackag

					)
					AS Source
			ON Target.CodItem = Source.CodItem AND  Target.CodClient = Source.CodClient AND Target.CodPackag = Source.CodPackag 
			WHEN MATCHED THEN
				UPDATE SET	TotQta		= Source.TotQta
						  , [Weight]	= Source.PesoMedio
						  , Tare		= Source.TaraMedia
                          , NumImb      = Source.NumImb
                          , Durata      = Source.Durata
			WHEN NOT MATCHED BY TARGET THEN
				INSERT (CodItem, CodClient, CodPackag, TotQta, [Weight], Tare, NumImb, Durata) 
                    VALUES (CodItem, CodClient, CodPackag, TotQta, PesoMedio, TaraMedia, NumImb, Durata)
			WHEN NOT MATCHED BY SOURCE THEN
                DELETE
			OUTPUT $action INTO @SummaryOfChanges;

		END
	--ELSE IF @source = 'ItemsRaw' -- carico da anagrafica
	--	BEGIN
	--		MERGE INTO Item2PackageClient AS Target
	--		USING (SELECT CodItem, ItemDescr, CodPlant, UnitWeight, CodItemGroup FROM ItemsRaw)
	--				AS Source
	--		ON Target.CodItem = Source.CodItem
	--		WHEN MATCHED THEN
	--			UPDATE SET ItemDescr = Source.ItemDescr, CodPlant = Source.CodPlant, UnitWeight = Source.UnitWeight, CodItemGroup = Source.CodItemGroup
	--		WHEN NOT MATCHED BY TARGET THEN
	--			INSERT (CodItem, ItemDescr, CodPlant, UnitWeight, CodItemGroup) VALUES (CodItem, ItemDescr, CodPlant, UnitWeight, CodItemGroup)
	--		OUTPUT $action INTO @SummaryOfChanges;

	--	END
		
	-- Query the results of the table variable.
	SELECT Change, COUNT(*) AS CountPerChange
	FROM @SummaryOfChanges
	GROUP BY Change;
END
GO
PRINT N'Creating [ext].[stp_mergePackage2Item]...';


GO



-- =============================================
-- Author:		S.E. Locatelli
-- Create date: 2014.01.15
-- Description:	Procedura per import dati in Package2Item da dati ProductionLogRaw
-- =============================================
CREATE PROCEDURE [ext].[stp_mergePackage2Item]
(
	@source NVARCHAR(20) = 'ProductionLog', -- nome della tabella sorgente tra ProductionLogRaw e ItemsRaw
	@dateFrom	DATETIME, -- data da cui iniziare a caricare
	@dateTo		DATETIME  -- data fino a cui caricare
)
AS
BEGIN
	SET NOCOUNT ON;
	

	-- Create a temporary table variable to hold the output actions.
	DECLARE @SummaryOfChanges TABLE(Change VARCHAR(20));
	
    -- import con MERGE... verifico tipo di caricamento richiesto!
	IF @source = 'ProductionLog' -- carico da tracciato produzione
		BEGIN
			MERGE INTO Package2Item AS Target
			USING	(
					--SELECT		dd.CodItem, plr.CodPackag, SUM(QtyOUT) AS TotQta, COUNT(*) AS NumEv
					--		  , SUM(QtyOUT) / COUNT(*) AS PesoMedio
					--		  , SUM(QtyEXT) / COUNT(*) AS TaraMedia
					--FROM		ext.ProductionLogRaw plr
					--			INNER JOIN DiesDet dd ON plr.CodDies = dd.CodDies
					--			WHERE ISNULL(plr.CodPackag, '') <> ''
					--GROUP BY	dd.CodItem, plr.CodPackag 
                    SELECT	
                             dd.CodItem
                           , pl.CodPackag
                           , SUM(QtyOUT) AS TotQta
                    --       , COUNT(*) AS NumEv
	                       , SUM(QtyOUT) / COUNT(*) AS PesoMedio
	                       , SUM(QtyEXT) / COUNT(*) AS TaraMedia
                           -- dati produttività imballo
                           , ROUND(SUM(QtyOUT* QuotaMan) / CASE WHEN SUM(QtyOUT) = 0 THEN 1 ELSE SUM(QtyOUT) END,0) as NumImb
                           , SUM(Duration) AS Durata
                    FROM	ProductionLog pl 
                    INNER JOIN DiesDet dd ON pl.CodDies=dd.CodDies
                    WHERE	pl.ProcessNum = '04'
                        AND pl.okPr = 1 AND pl.okQM = 1
                        AND ISNULL(pl.CodPackag, '') <> ''
                        AND	pl.EventStart BETWEEN @dateFrom AND @dateTo
                    GROUP BY dd.CodItem, pl.CodPackag
					)
					AS Source
			ON Target.CodItem = Source.CodItem AND Target.CodPackag = Source.CodPackag 
			WHEN MATCHED THEN
				UPDATE SET	TotQta		= Source.TotQta
						  , [Weight]	= Source.PesoMedio
						  , Tare		= Source.TaraMedia
                          , NumImb      = Source.NumImb
                          , Durata      = Source.Durata
			WHEN NOT MATCHED BY TARGET THEN
				INSERT (CodItem, CodPackag, TotQta, [Weight], Tare, NumImb, Durata) 
                    VALUES (CodItem, CodPackag, TotQta, PesoMedio, TaraMedia, NumImb, Durata)
			WHEN NOT MATCHED BY SOURCE THEN
                DELETE
			OUTPUT $action INTO @SummaryOfChanges;

		END
	--ELSE IF @source = 'ItemsRaw' -- carico da anagrafica
	--	BEGIN
	--		MERGE INTO Item2Package AS Target
	--		USING (SELECT CodItem, ItemDescr, CodPlant, UnitWeight, CodItemGroup FROM ItemsRaw)
	--				AS Source
	--		ON Target.CodItem = Source.CodItem
	--		WHEN MATCHED THEN
	--			UPDATE SET ItemDescr = Source.ItemDescr, CodPlant = Source.CodPlant, UnitWeight = Source.UnitWeight, CodItemGroup = Source.CodItemGroup
	--		WHEN NOT MATCHED BY TARGET THEN
	--			INSERT (CodItem, ItemDescr, CodPlant, UnitWeight, CodItemGroup) VALUES (CodItem, ItemDescr, CodPlant, UnitWeight, CodItemGroup)
	--		OUTPUT $action INTO @SummaryOfChanges;

	--	END
		
	-- Query the results of the table variable.
	SELECT Change, COUNT(*) AS CountPerChange
	FROM @SummaryOfChanges
	GROUP BY Change;
END
GO
PRINT N'Creating [ext].[stp_mergeItemDet]...';


GO

-- =============================================
-- Author:		S.E. Locatelli
-- Create date: 2013.11.27
-- Description:	Procedura per import dati in ItemDet da dati ProductionLogRaw/ItemsRaw
-- =============================================
CREATE PROCEDURE [ext].[stp_mergeItemDet]
(
	@source NVARCHAR(20) = 'ProductionLogRaw' -- nome della tabella sorgente tra ProductionLogRaw e ItemsRaw
)
AS
BEGIN
	SET NOCOUNT ON;
	

	-- Create a temporary table variable to hold the output actions.
	DECLARE @SummaryOfChanges TABLE(Change VARCHAR(20));
	
    -- import con MERGE... verifico tipo di caricamento richiesto!
	IF @source = 'ProductionLogRaw' -- carico da tracciato produzione
		BEGIN
			--MERGE INTO ItemDet AS Target
			--USING (SELECT DISTINCT CodItem FROM ext.ProductionLogRaw)
			--		AS Source
			--ON Target.CodItem = Source.CodItem 
			----WHEN MATCHED THEN
			----	UPDATE SET ClientName = Source.ClientName
			--WHEN NOT MATCHED BY TARGET THEN
			--	INSERT (CodItem, ItemDescr, CodPlant, UnitWeight, CodItemGroup) VALUES (CodItem, '#### - ' + CodItem, '', 0, '')
			--OUTPUT $action INTO @SummaryOfChanges;
			select 1
		END
	ELSE IF @source = 'ItemsRaw' -- carico da anagrafica
		BEGIN
			MERGE INTO ItemDet AS Target
			USING (SELECT CodItem, ItemDescr, CodPlant, UnitWeight, CodItemGroup, Class01, Class02, Class03, Class04, Class05 FROM ext.ItemsRaw)
					AS Source
			ON Target.CodItem = Source.CodItem
			WHEN MATCHED THEN
				UPDATE SET ItemDescr = Source.ItemDescr, CodPlant = Source.CodPlant, UnitWeight = Source.UnitWeight, CodItemGroup = Source.CodItemGroup, Class01 = Source.Class01, Class02 = Source.Class02, Class03 = Source.Class03, Class04 = Source.Class04, Class05 = Source.Class05
			WHEN NOT MATCHED BY TARGET THEN
				INSERT (CodItem, ItemDescr, CodPlant, UnitWeight, CodItemGroup, Class01, Class02, Class03, Class04, Class05) VALUES (CodItem, ItemDescr, CodPlant, UnitWeight, CodItemGroup, Class01, Class02, Class03, Class04, Class05)
			OUTPUT $action INTO @SummaryOfChanges;

		END
		
	-- Query the results of the table variable.
	SELECT Change, COUNT(*) AS CountPerChange
	FROM @SummaryOfChanges
	GROUP BY Change;
END
GO
PRINT N'Creating [ext].[stp_mergeClientDet]...';


GO



-- =============================================
-- Author:		S.E. Locatelli
-- Create date: 2013.11.27
-- Description:	Procedura per import dati in ClientDet da dati ProductionLogRaw/ClientsRaw
-- =============================================
CREATE PROCEDURE [ext].[stp_mergeClientDet]
(
	@source NVARCHAR(20) = 'ProductionLogRaw' -- nome della tabella sorgente tra ProductionLogRaw e ClientsRaw
)
AS
BEGIN
	SET NOCOUNT ON;
	
	-- Create a temporary table variable to hold the output actions.
	DECLARE @SummaryOfChanges TABLE(Change VARCHAR(20));

    -- import con MERGE... verifico tipo di caricamento richiesto!
	IF @source = 'ProductionLogRaw' -- carico da tracciato produzione
		BEGIN
			MERGE INTO ClientDet AS Target
			USING (SELECT DISTINCT CodClient FROM ext.ProductionLogRaw)
					AS Source
			ON Target.CodClient = Source.CodClient
			--WHEN MATCHED THEN
			--	UPDATE SET ClientName = Source.ClientName
			WHEN NOT MATCHED BY TARGET THEN
				INSERT (CodClient, ClientName, CodAg, ZipCode, City, [State], Nation, TranspZone) VALUES (CodClient, '#### - ' + CodClient, '', '', '', '', '', '')
			OUTPUT $action INTO @SummaryOfChanges;

		END
	ELSE IF @source = 'ClientsRaw' -- carico da anagrafica
		BEGIN
			MERGE INTO ClientDet AS Target
			USING (SELECT DISTINCT CodClient, ClientName, CodAg, ZipCode, City, [State], Nation, TranspZone FROM ext.ClientsRaw)
					AS Source
			ON Target.CodClient = Source.CodClient
			WHEN MATCHED THEN
				UPDATE SET ClientName = Source.ClientName, CodAg = Source.CodAg, ZipCode = Source.ZipCode, City = Source.City,  [State] = Source.[State],  Nation = Source.Nation,  TranspZone = Source.TranspZone
			WHEN NOT MATCHED BY TARGET THEN
				INSERT (CodClient, ClientName, CodAg, ZipCode, City, [State], Nation, TranspZone)  VALUES (CodClient, ClientName, CodAg, ZipCode, City, [State], Nation, TranspZone) 
			OUTPUT $action INTO @SummaryOfChanges;

		END
		
	-- Query the results of the table variable.
	SELECT Change, COUNT(*) AS CountPerChange
	FROM @SummaryOfChanges
	GROUP BY Change;
END
GO
PRINT N'Creating [ext].[stp_mergeTranspCostDet]...';


GO

-- =============================================
-- Author:		S.E. Locatelli
-- Create date: 2014.01.16
-- Description:	Procedura per import dati in ClientDet da dati ProductionLogRaw/ClientsRaw
-- =============================================
CREATE PROCEDURE [ext].[stp_mergeTranspCostDet]
(
	@source NVARCHAR(20) = 'TranspCostRaw' -- nome della tabella sorgente tra ProductionLogRaw e ClientsRaw
)
AS
BEGIN
	SET NOCOUNT ON;
	
	-- Create a temporary table variable to hold the output actions.
	DECLARE @SummaryOfChanges TABLE(Change VARCHAR(20));

    -- import con MERGE... verifico tipo di caricamento richiesto!
	IF @source = 'TranspCostRaw' -- carico da anagrafica
		BEGIN
			MERGE INTO TranspCostDet AS Target
			USING (SELECT DISTINCT TranspZone, TranspCost FROM ext.TranspCostRaw)
					AS Source
			ON Target.TranspZone = Source.TranspZone
			WHEN MATCHED THEN
				UPDATE SET TranspCost = Source.TranspCost
			WHEN NOT MATCHED BY TARGET THEN
				INSERT (TranspZone, TranspCost)  VALUES (TranspZone, TranspCost) 
			OUTPUT $action INTO @SummaryOfChanges;

		END
		
	-- Query the results of the table variable.
	SELECT Change, COUNT(*) AS CountPerChange
	FROM @SummaryOfChanges
	GROUP BY Change;
END
GO
PRINT N'Creating [ext].[stp_mergePackage2ItemClient_OLD]...';


GO

-- =============================================
-- Author:		S.E. Locatelli
-- Create date: 2013.11.27
-- Description:	Procedura per import dati in Package2ItemClient da dati ProductionLogRaw
-- =============================================
CREATE PROCEDURE [ext].[stp_mergePackage2ItemClient_OLD]
(
	@source NVARCHAR(20) = 'ProductionLogRaw' -- nome della tabella sorgente tra ProductionLogRaw e ItemsRaw
)
AS
BEGIN
	SET NOCOUNT ON;
	

	---- Create a temporary table variable to hold the output actions.
	--DECLARE @SummaryOfChanges TABLE(Change VARCHAR(20));
	
 --   -- import con MERGE... verifico tipo di caricamento richiesto!
	--IF @source = 'ProductionLogRaw' -- carico da tracciato produzione
	--	BEGIN
	--		MERGE INTO Package2ItemClient AS Target
	--		USING	(
	--				SELECT		dd.CodItem, plr.CodClient, plr.CodPackag, SUM(QtyOUT) AS TotQta, COUNT(*) AS NumEv
	--						  , SUM(QtyOUT) / COUNT(*) AS PesoMedio
	--						  , SUM(QtyEXT) / COUNT(*) AS TaraMedia
	--				FROM		ext.ProductionLogRaw plr
	--							INNER JOIN DiesDet dd ON plr.CodDies = dd.CodDies
	--							WHERE ISNULL(plr.CodPackag, '') <> ''
	--				GROUP BY	dd.CodItem, plr.CodClient, plr.CodPackag 
	--				)
	--				AS Source
	--		ON Target.CodItem = Source.CodItem AND  Target.CodClient = Source.CodClient AND Target.CodPackag = Source.CodPackag 
	--		WHEN MATCHED THEN
	--			UPDATE SET	TotQty		= Source.TotQta
	--					  , [Weight]	= Source.PesoMedio
	--					  , Tare		= Source.TaraMedia
	--		WHEN NOT MATCHED BY TARGET THEN
	--			INSERT (CodItem, CodClient, CodPackag, TotQty, [Weight], Tare) VALUES (CodItem, CodClient, CodPackag, TotQta, PesoMedio, TaraMedia)
	--		OUTPUT $action INTO @SummaryOfChanges;

	--	END
	----ELSE IF @source = 'ItemsRaw' -- carico da anagrafica
	----	BEGIN
	----		MERGE INTO Item2PackageClient AS Target
	----		USING (SELECT CodItem, ItemDescr, CodPlant, UnitWeight, CodItemGroup FROM ItemsRaw)
	----				AS Source
	----		ON Target.CodItem = Source.CodItem
	----		WHEN MATCHED THEN
	----			UPDATE SET ItemDescr = Source.ItemDescr, CodPlant = Source.CodPlant, UnitWeight = Source.UnitWeight, CodItemGroup = Source.CodItemGroup
	----		WHEN NOT MATCHED BY TARGET THEN
	----			INSERT (CodItem, ItemDescr, CodPlant, UnitWeight, CodItemGroup) VALUES (CodItem, ItemDescr, CodPlant, UnitWeight, CodItemGroup)
	----		OUTPUT $action INTO @SummaryOfChanges;

	----	END
		
	---- Query the results of the table variable.
	--SELECT Change, COUNT(*) AS CountPerChange
	--FROM @SummaryOfChanges
	--GROUP BY Change;
END
GO
PRINT N'Creating [ext].[stp_mergePackage2]...';


GO




-- =============================================
-- Author:		S.E. Locatelli
-- Create date: 2014.01.15
-- Description:	Procedura per import dati in Package2Item da dati ProductionLogRaw
-- =============================================
CREATE PROCEDURE [ext].[stp_mergePackage2]
(
	@source     NVARCHAR(20) = 'ProductionLog', -- nome della tabella sorgente tra ProductionLogRaw e ItemsRaw
	@dateFrom	DATETIME, -- data da cui iniziare a caricare
	@dateTo		DATETIME  -- data fino a cui caricare
)
AS
BEGIN
	SET NOCOUNT ON;
	

	-- Create a temporary table variable to hold the output actions.
	DECLARE @SummaryOfChanges TABLE(Change VARCHAR(20));
	
    -- import con MERGE... verifico tipo di caricamento richiesto!
	IF @source = 'ProductionLog' -- carico da tracciato produzione
		BEGIN
			MERGE INTO Package2 AS Target
			USING	(
					--SELECT		plr.CodPackag, SUM(QtyOUT) AS TotQta, COUNT(*) AS NumEv
					--		  , SUM(QtyOUT) / COUNT(*) AS PesoMedio
					--		  , SUM(QtyEXT) / COUNT(*) AS TaraMedia
					--FROM		ext.ProductionLogRaw plr
					--			INNER JOIN DiesDet dd ON plr.CodDies = dd.CodDies
					--			WHERE ISNULL(plr.CodPackag, '') <> ''
					--GROUP BY	plr.CodPackag 
                    SELECT 			
		                    pl.CodPackag
                          , SUM(QtyOUT) AS TotQta
--                          , COUNT(*) AS NumEv
                          , SUM(QtyOUT) / COUNT(*) AS PesoMedio
	                      , SUM(QtyEXT) / COUNT(*) AS TaraMedia

                          -- dati produttività imballo
	                      , ROUND(SUM(QtyOUT * QuotaMan) / CASE WHEN SUM(QtyOUT) = 0 THEN 1 ELSE SUM(QtyOUT) END,0) as NumImb
                    --	  , SUM(QtyOUT) AS TotOut      -- unificata a TotQta
	                      , SUM(Duration) AS Durata
                    FROM	ProductionLog pl 
                    INNER JOIN DiesDet dd ON pl.CodDies=dd.CodDies
                    WHERE	pl.ProcessNum = '04'
	                    AND pl.okPr = 1 AND pl.okQM = 1                  
                        AND ISNULL(pl.CodPackag, '') <> ''                -- cmq filtro righe con package VUOTO
	                    AND	pl.EventStart BETWEEN @dateFrom AND @dateTo
                    GROUP BY pl.CodPackag
					)
					AS Source
			ON Target.CodPackag = Source.CodPackag 
			WHEN MATCHED THEN
				UPDATE SET	TotQta		= Source.TotQta
						  , [Weight]	= Source.PesoMedio
						  , Tare		= Source.TaraMedia
                          , NumImb      = Source.NumImb
                          , Durata      = Source.Durata
			WHEN NOT MATCHED BY TARGET THEN
				INSERT (CodPackag, TotQta, [Weight], Tare, NumImb, Durata) 
                    VALUES (CodPackag, TotQta, PesoMedio, TaraMedia, NumImb, Durata)
			WHEN NOT MATCHED BY SOURCE THEN
                DELETE
			OUTPUT $action INTO @SummaryOfChanges;

		END
	--ELSE IF @source = 'ItemsRaw' -- carico da anagrafica
	--	BEGIN
	--		MERGE INTO Item2Package AS Target
	--		USING (SELECT CodItem, ItemDescr, CodPlant, UnitWeight, CodItemGroup FROM ItemsRaw)
	--				AS Source
	--		ON Target.CodItem = Source.CodItem
	--		WHEN MATCHED THEN
	--			UPDATE SET ItemDescr = Source.ItemDescr, CodPlant = Source.CodPlant, UnitWeight = Source.UnitWeight, CodItemGroup = Source.CodItemGroup
	--		WHEN NOT MATCHED BY TARGET THEN
	--			INSERT (CodItem, ItemDescr, CodPlant, UnitWeight, CodItemGroup) VALUES (CodItem, ItemDescr, CodPlant, UnitWeight, CodItemGroup)
	--		OUTPUT $action INTO @SummaryOfChanges;

	--	END
		
	-- Query the results of the table variable.
	SELECT Change, COUNT(*) AS CountPerChange
	FROM @SummaryOfChanges
	GROUP BY Change;
END
GO
PRINT N'Creating [ext].[stp_filterProductionLogRow]...';


GO


-- =============================================
-- Author:		
-- Create date: 2013.11.29
-- Description:	Procedura per pulizia dati della tabella ext.ProductionLogRaw
--
-- Use: 
--      EXECUTE ext.stp_filterProductionLogRow 0  -- selezione record
--      EXECUTE ext.stp_filterProductionLogRow 1  -- cancellazione record
--
--      SELECT * FROM tmp.ExcludeCondFilter          -- Tabella con i filtri
--      SELECT * FROM ext.ProductionLogRaw_KO        -- Tabella dove eseguo delete
--
-- =============================================
CREATE PROCEDURE [ext].[stp_filterProductionLogRow]
( 
    @flgDelete AS TINYINT = 0 -- 0 = solo select    1 = fa delete 
)
AS
BEGIN

--  DECLARE @flgDelete AS TINYINT = 1;    -- 0 

    DECLARE @Sql AS NVARCHAR(MAX) = '';
    DECLARE @TotRighe AS INT = 0;
    DECLARE @Riga AS INT = 1;
    DECLARE @WhereCond AS NVARCHAR(4000);

    IF OBJECT_ID('tempdb..#tmpTable') IS NOT NULL
        DROP TABLE #tmpTable

    -- creo sql di base x select o delete 
    IF @flgDelete = 0  -- voglio fare solo select
      SET @Sql = 'SELECT * FROM ext.ProductionLogRaw WHERE 1=0'   -- per test
    ELSE
      SET @Sql = 'DELETE FROM ext.ProductionLogRaw
                  WITH (TABLOCK)
                  OUTPUT deleted.* INTO ext.ProductionLogRaw_KO    -- salvo i record cancellati in tabella KO
                         ( EventStart, EventEnd, CodPlant, ProcessNum, NrPos, CodDies, CodClient, OrderNum, BatchNum, ProcessType, EventType, RawMat, CodPackag, QtyIN, QtyOUT, QtyEXT, NumIN, NumOUT, QuotaPlant, QuotaMan, Tags )
                  WHERE 1=0'

    -- carico in tabella i filtri ( record da cancellare )
    SELECT ROW_NUMBER() OVER ( ORDER BY TableName, FieldName) AS Riga, *
        INTO #tmpTable
    FROM tmp.ExcludeCondFilter
    WHERE TableName = 'ProductionLogRaw'

    SET @TotRighe = @@ROWCOUNT;

    -- accodo le condizioni di where allo statement iniziale ( collegate con OR )
    IF @TotRighe > 0
    BEGIN
      WHILE @Riga <= @TotRighe
       BEGIN
        SELECT @WhereCond = WhereCond FROM #tmpTable WHERE Riga = @Riga

        SET @Sql = @Sql + ' OR ' + @WhereCond;
        SET @Riga = @Riga + 1;
       END
    END

    -- Ritorno la select eseguita
    SELECT @Sql
    -- =======================================================
    -- Eseguo la select/delete e ritorno i record elaborati
    -- =======================================================
    EXEC sp_executesql @Sql 
    SELECT @@ROWCOUNT

-- SELECT * FROM ext.ProductionLogRaw_KO 

    IF OBJECT_ID('tempdb..#tmpTable') IS NOT NULL
        DROP TABLE #tmpTable
END
GO
PRINT N'Creating [ext].[stp_mergePackagDet]...';


GO


-- =============================================
-- Author:		S.E. Locatelli
-- Create date: 2013.11.29
-- Description:	Procedura per import dati in PackagDet da dati ProductionLogRaw/PackagRaw
-- =============================================
CREATE PROCEDURE [ext].[stp_mergePackagDet]
(
	@source NVARCHAR(20) = 'ProductionLogRaw' -- nome della tabella sorgente tra ProductionLogRaw e PackagRaw
)
AS
BEGIN
	SET NOCOUNT ON;
	
	-- Create a temporary table variable to hold the output actions.
	DECLARE @SummaryOfChanges TABLE(Change VARCHAR(20));

    -- import con MERGE... verifico tipo di caricamento richiesto!
	IF @source = 'ProductionLogRaw' -- carico da tracciato produzione
		BEGIN
			MERGE INTO PackagDet AS Target
			USING (SELECT DISTINCT CodPackag FROM ext.ProductionLogRaw)
					AS Source
			ON Target.CodPackag = Source.CodPackag
			--WHEN MATCHED THEN
			--	UPDATE SET PackagName = Source.PackagName
			WHEN NOT MATCHED BY TARGET THEN
				INSERT (CodPackag, PackagDesc, RMCost, RMWeight) VALUES (CodPackag, '#### - ' + CodPackag, 0, 0)
			OUTPUT $action INTO @SummaryOfChanges;

		END
	ELSE IF @source = 'PackagRaw' -- carico da anagrafica
		BEGIN
			MERGE INTO PackagDet AS Target
			USING (SELECT CodPackag, PackagDesc, RMCost, RMWeight FROM ext.PackagRaw)
					AS Source
			ON Target.CodPackag = Source.CodPackag
			WHEN MATCHED THEN
				UPDATE SET PackagDesc = Source.PackagDesc, RMCost = Source.RMCost, RMWeight = Source.RMWeight
			WHEN NOT MATCHED BY TARGET THEN
				INSERT (CodPackag, PackagDesc, RMCost, RMWeight)  VALUES (CodPackag, PackagDesc, RMCost, RMWeight) 
			OUTPUT $action INTO @SummaryOfChanges;

		END
		
	-- Query the results of the table variable.
	SELECT Change, COUNT(*) AS CountPerChange
	FROM @SummaryOfChanges
	GROUP BY Change;
END
GO
PRINT N'Creating [ext].[stp_mergeDiesGroupDet]...';


GO


-- =============================================
-- Author:		S.E. Locatelli
-- Create date: 2014.01.08
-- Description:	Procedura per import dati in DiesDet da dati DiesGroupRaw
--              Il caricamento principale avviene tramite DiesRaw, questa
--              serve solo per completare i dati mancanti
-- =============================================
CREATE PROCEDURE [ext].[stp_mergeDiesGroupDet]

AS
BEGIN
	SET NOCOUNT ON;
	
	-- Create a temporary table variable to hold the output actions.
	DECLARE @SummaryOfChanges TABLE(Change VARCHAR(20));

	SET XACT_ABORT ON

	BEGIN TRAN

		-- vado ad aggiornare i dati dei gruppi di matrici SOLO x i campi <> 0 ( li ritengo come non passati )
		MERGE INTO dbo.DiesGroupDet AS Target
		USING ( SELECT * FROM ext.DiesGroupRaw ) 
				AS Source
		ON Target.CodDiesGroup = Source.CodDiesGroup
		WHEN MATCHED THEN
			UPDATE SET Price   = CASE Source.Price   WHEN 0 THEN Target.Price   ELSE Source.Price   END
                     , QtyTot  = CASE Source.QtyTot  WHEN 0 THEN Target.QtyTot  ELSE Source.QtyTot  END
                     , QtyEOL  = CASE Source.QtyEOL  WHEN 0 THEN Target.QtyEOL  ELSE Source.QtyEOL  END
                     , ExpLife = CASE Source.ExpLife WHEN 0 THEN Target.ExpLife ELSE Source.ExpLife END
                     , EOLLife = CASE Source.EOLLife WHEN 0 THEN Target.EOLLife ELSE Source.EOLLife END
                     , DateMod = GETDATE()
                     , UserMod = 'UPDATE_DiesGroupRaw'
		WHEN NOT MATCHED BY TARGET THEN
			INSERT ( CodDiesGroup, Price, QtyTot, QtyEOL, ExpLife, EOLLife, DateMod, UserMod )
            VALUES ( Source.CodDiesGroup, Source.Price, Source.QtyTot, Source.QtyEOL, Source.ExpLife,  Source.EOLLife, GETDATE(), 'INSERT_DiesGroupRaw' )
--          VALUES ( CodDiesGroup, 0, 1, 0, 0.1, 0.1 ) -- mi da errori in calcoli successivi altrimenti con 0 a ExpLife e EOLLife
		OUTPUT $action INTO @SummaryOfChanges;

	COMMIT TRAN
		
	-- Query the results of the table variable.
	SELECT Change, COUNT(*) AS CountPerChange
	FROM @SummaryOfChanges
	GROUP BY Change;
END
GO
PRINT N'Creating [ext].[stp_mergeAgentsDet]...';


GO

-- =============================================
-- Author:		S.E. Locatelli
-- Create date: 2013.12.03
-- Description:	Procedura per import dati in AgentsDet da dati ClientsRaw
-- =============================================
CREATE PROCEDURE [ext].[stp_mergeAgentsDet]
(
	@source NVARCHAR(20) = 'ClientsRaw' -- nome della tabella sorgente tra ProductionLogRaw e AgentssRaw
)
AS
BEGIN
	SET NOCOUNT ON;
	
	-- Create a temporary table variable to hold the output actions.
	DECLARE @SummaryOfChanges TABLE(Change VARCHAR(20));

    -- import con MERGE... verifico tipo di caricamento richiesto!
	IF @source = 'ClientsRaw' -- carico da anagrafica
		BEGIN
			MERGE INTO AgentsDet AS Target
			USING (SELECT DISTINCT CodAg FROM ext.ClientsRaw)
					AS Source
			ON Target.CodAg = Source.CodAg
			--WHEN MATCHED THEN
			--	UPDATE SET AgentsName = Source.AgentsName, CodAg = Source.CodAg, ZipCode = Source.ZipCode, City = Source.City,  [State] = Source.[State],  Nation = Source.Nation
			WHEN NOT MATCHED BY TARGET THEN
				INSERT (CodAg, Firstname, Lastname, QuotaProvvAg)  VALUES (CodAg, '#### - '+ CodAg, '#### - ' + CodAg, 0) 
			OUTPUT $action INTO @SummaryOfChanges;

		END
		
	-- Query the results of the table variable.
	SELECT Change, COUNT(*) AS CountPerChange
	FROM @SummaryOfChanges
	GROUP BY Change;
END
GO
PRINT N'Creating [ext].[stp_updateProductionLog]...';


GO

-- =============================================
-- Author:		S.E. Locatelli
-- Create date: 2013.11.29
-- Description:	Procedura per import dati in ProductionLog da dati ProductionLogRaw
--
-- ATTENZIONE: dato l'intervallo temporale in ext.ProductionLogRaw eventuali dati precedenti in dbo.ProductionLog saranno eliminati
-- =============================================
CREATE PROCEDURE [ext].[stp_updateProductionLog]

AS
BEGIN
	SET NOCOUNT ON;

	-- Create a temporary table variable to hold the output actions.
	DECLARE  @deleted	INT = 0
			,@inserted	INT = 0
			,@fromDate	DATETIME = GETDATE()
			,@toDate	DATETIME = GETDATE()
	
	-- primo step: calcolo inizio/fine periodo...
	SELECT @fromDate=MIN(EventStart), @toDate=MAX(EventStart) FROM ext.ProductionLogRaw

	
	-- secondo step: elimino dal tracciato tutti i dati dal periodo indicato
	DELETE FROM dbo.ProductionLog
	WHERE EventStart BETWEEN @fromDate AND @toDate

	SELECT @deleted = ISNULL(@@ROWCOUNT,0)

	-- inserisco i nuovi dati
	INSERT INTO dbo.ProductionLog
	SELECT * FROM ext.ProductionLogRaw
	
	SELECT @inserted = ISNULL(@@ROWCOUNT,0)
    
	-- riporto in output quanto eliminato/inserito
	SELECT @deleted as RecDeleted, @inserted as RecInserted

END
GO
PRINT N'Creating [ext].[stp_mergeRawMat]...';


GO

-- =============================================
-- Author:		S.E. Locatelli
-- Create date: 2013.12.02
-- Description:	Procedura per import dati in PackagDet da dati ProductionLogRaw/PackagRaw
-- =============================================
CREATE PROCEDURE [ext].[stp_mergeRawMat]
(
	@source NVARCHAR(20) = 'ProductionLogRaw' -- nome della tabella sorgente tra ProductionLogRaw e PackagRaw
)
AS
BEGIN
	SET NOCOUNT ON;
	
	-- Create a temporary table variable to hold the output actions.
	DECLARE @SummaryOfChanges TABLE(Change VARCHAR(20));

    -- import con MERGE... verifico tipo di caricamento richiesto!
	IF @source = 'ProductionLogRaw' -- carico da tracciato produzione
		BEGIN
			MERGE INTO RawMatDet AS Target
			USING (SELECT DISTINCT RawMat FROM ext.ProductionLogRaw)
					AS Source
			ON Target.RawMat = Source.RawMat
			--WHEN MATCHED THEN
			--	UPDATE SET PackagName = Source.PackagName
			WHEN NOT MATCHED BY TARGET THEN
				INSERT (RawMat, ProcCost, ProcYield, CSR) VALUES (RawMat, 0, 0, 0)
			OUTPUT $action INTO @SummaryOfChanges;

		END
	--ELSE IF @source = 'PackagRaw' -- carico da anagrafica
	--	BEGIN
	--		MERGE INTO PackagDet AS Target
	--		USING (SELECT CodPackag, PackagDesc, RMCost, RMWeight, Tare, FullWeight FROM ext.PackagRaw)
	--				AS Source
	--		ON Target.CodPackag = Source.CodPackag
	--		WHEN MATCHED THEN
	--			UPDATE SET PackagDesc = Source.PackagDesc, RMCost = Source.RMCost, RMWeight = Source.RMWeight, Tare = Source.Tare,  FullWeight = Source.FullWeight
	--		WHEN NOT MATCHED BY TARGET THEN
	--			INSERT (CodPackag, PackagDesc, RMCost, RMWeight, Tare, FullWeight)  VALUES (CodPackag, PackagDesc, RMCost, RMWeight, Tare, FullWeight) 
	--		OUTPUT $action INTO @SummaryOfChanges;

	--	END
		
	-- Query the results of the table variable.
	SELECT Change, COUNT(*) AS CountPerChange
	FROM @SummaryOfChanges
	GROUP BY Change;
END
GO
PRINT N'Creating [ext].[stp_mergePackage2_OLD]...';


GO

-- =============================================
-- Author:		S.E. Locatelli
-- Create date: 2014.01.15
-- Description:	Procedura per import dati in Package2Item da dati ProductionLogRaw
-- =============================================
CREATE PROCEDURE [ext].[stp_mergePackage2_OLD]
(
	@source NVARCHAR(20) = 'ProductionLogRaw' -- nome della tabella sorgente tra ProductionLogRaw e ItemsRaw
)
AS
BEGIN
	SET NOCOUNT ON;
	

	---- Create a temporary table variable to hold the output actions.
	--DECLARE @SummaryOfChanges TABLE(Change VARCHAR(20));
	
 --   -- import con MERGE... verifico tipo di caricamento richiesto!
	--IF @source = 'ProductionLogRaw' -- carico da tracciato produzione
	--	BEGIN
	--		MERGE INTO Package2 AS Target
	--		USING	(
	--				SELECT		plr.CodPackag, SUM(QtyOUT) AS TotQta, COUNT(*) AS NumEv
	--						  , SUM(QtyOUT) / COUNT(*) AS PesoMedio
	--						  , SUM(QtyEXT) / COUNT(*) AS TaraMedia
	--				FROM		ext.ProductionLogRaw plr
	--							INNER JOIN DiesDet dd ON plr.CodDies = dd.CodDies
	--							WHERE ISNULL(plr.CodPackag, '') <> ''
	--				GROUP BY	plr.CodPackag 
	--				)
	--				AS Source
	--		ON Target.CodPackag = Source.CodPackag 
	--		WHEN MATCHED THEN
	--			UPDATE SET	TotQty		= Source.TotQta
	--					  , [Weight]	= Source.PesoMedio
	--					  , Tare		= Source.TaraMedia
	--		WHEN NOT MATCHED BY TARGET THEN
	--			INSERT (CodPackag, TotQty, [Weight], Tare) VALUES (CodPackag, TotQta, PesoMedio, TaraMedia)
	--		OUTPUT $action INTO @SummaryOfChanges;

	--	END
	----ELSE IF @source = 'ItemsRaw' -- carico da anagrafica
	----	BEGIN
	----		MERGE INTO Item2Package AS Target
	----		USING (SELECT CodItem, ItemDescr, CodPlant, UnitWeight, CodItemGroup FROM ItemsRaw)
	----				AS Source
	----		ON Target.CodItem = Source.CodItem
	----		WHEN MATCHED THEN
	----			UPDATE SET ItemDescr = Source.ItemDescr, CodPlant = Source.CodPlant, UnitWeight = Source.UnitWeight, CodItemGroup = Source.CodItemGroup
	----		WHEN NOT MATCHED BY TARGET THEN
	----			INSERT (CodItem, ItemDescr, CodPlant, UnitWeight, CodItemGroup) VALUES (CodItem, ItemDescr, CodPlant, UnitWeight, CodItemGroup)
	----		OUTPUT $action INTO @SummaryOfChanges;

	----	END
		
	---- Query the results of the table variable.
	--SELECT Change, COUNT(*) AS CountPerChange
	--FROM @SummaryOfChanges
	--GROUP BY Change;
END
GO
PRINT N'Creating [ext].[stp_mergePackage2Item_OLD]...';


GO

-- =============================================
-- Author:		S.E. Locatelli
-- Create date: 2014.01.15
-- Description:	Procedura per import dati in Package2Item da dati ProductionLogRaw
-- =============================================
CREATE PROCEDURE [ext].[stp_mergePackage2Item_OLD]
(
	@source NVARCHAR(20) = 'ProductionLogRaw' -- nome della tabella sorgente tra ProductionLogRaw e ItemsRaw
)
AS
BEGIN
	SET NOCOUNT ON;
	

	---- Create a temporary table variable to hold the output actions.
	--DECLARE @SummaryOfChanges TABLE(Change VARCHAR(20));
	
 --   -- import con MERGE... verifico tipo di caricamento richiesto!
	--IF @source = 'ProductionLogRaw' -- carico da tracciato produzione
	--	BEGIN
	--		MERGE INTO Package2Item AS Target
	--		USING	(
	--				SELECT		dd.CodItem, plr.CodPackag, SUM(QtyOUT) AS TotQta, COUNT(*) AS NumEv
	--						  , SUM(QtyOUT) / COUNT(*) AS PesoMedio
	--						  , SUM(QtyEXT) / COUNT(*) AS TaraMedia
	--				FROM		ext.ProductionLogRaw plr
	--							INNER JOIN DiesDet dd ON plr.CodDies = dd.CodDies
	--							WHERE ISNULL(plr.CodPackag, '') <> ''
	--				GROUP BY	dd.CodItem, plr.CodPackag 
	--				)
	--				AS Source
	--		ON Target.CodItem = Source.CodItem AND Target.CodPackag = Source.CodPackag 
	--		WHEN MATCHED THEN
	--			UPDATE SET	TotQty		= Source.TotQta
	--					  , [Weight]	= Source.PesoMedio
	--					  , Tare		= Source.TaraMedia
	--		WHEN NOT MATCHED BY TARGET THEN
	--			INSERT (CodItem, CodPackag, TotQty, [Weight], Tare) VALUES (CodItem, CodPackag, TotQta, PesoMedio, TaraMedia)
	--		OUTPUT $action INTO @SummaryOfChanges;

	--	END
	----ELSE IF @source = 'ItemsRaw' -- carico da anagrafica
	----	BEGIN
	----		MERGE INTO Item2Package AS Target
	----		USING (SELECT CodItem, ItemDescr, CodPlant, UnitWeight, CodItemGroup FROM ItemsRaw)
	----				AS Source
	----		ON Target.CodItem = Source.CodItem
	----		WHEN MATCHED THEN
	----			UPDATE SET ItemDescr = Source.ItemDescr, CodPlant = Source.CodPlant, UnitWeight = Source.UnitWeight, CodItemGroup = Source.CodItemGroup
	----		WHEN NOT MATCHED BY TARGET THEN
	----			INSERT (CodItem, ItemDescr, CodPlant, UnitWeight, CodItemGroup) VALUES (CodItem, ItemDescr, CodPlant, UnitWeight, CodItemGroup)
	----		OUTPUT $action INTO @SummaryOfChanges;

	----	END
		
	---- Query the results of the table variable.
	--SELECT Change, COUNT(*) AS CountPerChange
	--FROM @SummaryOfChanges
	--GROUP BY Change;
END
GO
PRINT N'Creating [ext].[stp_mergeCost2Plant]...';


GO



-- =============================================
-- Author:		S.E. Locatelli
-- Create date: 2013.12.03
-- Description:	Procedura per import dati in Cost2Plant da dati ProductionLogRaw
-- =============================================
CREATE PROCEDURE [ext].[stp_mergeCost2Plant]
(
	@source NVARCHAR(20) = 'ProductionLogRaw' -- nome della tabella sorgente tra ProductionLogRaw
)
AS
BEGIN
	SET NOCOUNT ON;
	
	-- Create a temporary table variable to hold the output actions.
	DECLARE @SummaryOfChanges TABLE(Change VARCHAR(20));

    -- import con MERGE... verifico tipo di caricamento richiesto!
	IF @source = 'ProductionLogRaw' -- carico da tracciato produzione
		BEGIN
			MERGE INTO Cost2Plant AS Target
			USING (SELECT DISTINCT CodPlant, ProcessNum FROM ext.ProductionLogRaw)
					AS Source
			ON Target.CodPlant = Source.CodPlant
			--WHEN MATCHED THEN
			--	UPDATE SET PackagName = Source.PackagName
			WHEN NOT MATCHED BY TARGET THEN
				INSERT (CodPlant, ProcessNum, FC, VC, OH, SC, QuotaPlantStd, QuotaManStd) VALUES (CodPlant, ProcessNum, 0,0,0,0,1,1 )   --> i valori sono stati caricati a mano???
			OUTPUT $action INTO @SummaryOfChanges;

		END
	--ELSE IF @source = 'PackagRaw' -- carico da anagrafica
	--	BEGIN
	--		MERGE INTO PackagDet AS Target
	--		USING (SELECT CodPackag, PackagDesc, RMCost, RMWeight, Tare, FullWeight FROM ext.PackagRaw)
	--				AS Source
	--		ON Target.CodPackag = Source.CodPackag
	--		WHEN MATCHED THEN
	--			UPDATE SET PackagDesc = Source.PackagDesc, RMCost = Source.RMCost, RMWeight = Source.RMWeight, Tare = Source.Tare,  FullWeight = Source.FullWeight
	--		WHEN NOT MATCHED BY TARGET THEN
	--			INSERT (CodPackag, PackagDesc, RMCost, RMWeight, Tare, FullWeight)  VALUES (CodPackag, PackagDesc, RMCost, RMWeight, Tare, FullWeight) 
	--		OUTPUT $action INTO @SummaryOfChanges;

	--	END
		
	-- Query the results of the table variable.
	SELECT Change, COUNT(*) AS CountPerChange
	FROM @SummaryOfChanges
	GROUP BY Change;
END
GO
PRINT N'Creating [ext].[stp_mergeDiesDet]...';


GO



-- =============================================
-- Author:		S.E. Locatelli
-- Create date: 2013.12.02
-- Description:	Procedura per import dati in DiesDet da dati ProductionLogRaw/DiesRaw
-- =============================================
CREATE PROCEDURE [ext].[stp_mergeDiesDet]

AS
BEGIN
	SET NOCOUNT ON;
	
	-- Create a temporary table variable to hold the output actions.
	DECLARE @SummaryOfChanges TABLE(Change VARCHAR(20));

	SET XACT_ABORT ON

	BEGIN tran

        -- =======================================
		-- ora aggiungiamo eventuali item mancanti
        -- =======================================
		MERGE INTO ItemDet AS Target
		USING (SELECT DISTINCT CodItem FROM ext.DiesRaw)
				AS Source
		ON Target.CodItem = Source.CodItem 
		--WHEN MATCHED THEN
		--	UPDATE SET ClientName = Source.ClientName
		WHEN NOT MATCHED BY TARGET THEN
			INSERT (CodItem, ItemDescr, CodPlant, UnitWeight, CodItemGroup) VALUES (CodItem, '#### - ' + CodItem, '', 0, '')
		OUTPUT $action INTO @SummaryOfChanges;

        -- =================================================
		-- Carico i dati dei GRUPPI DI MATRICI ( DiesGroupDet ) mancanti
        -- =================================================
		MERGE INTO dbo.DiesGroupDet AS Target
		USING ( 
                SELECT    CodDiesGroup
                        , ISNULL ( AVG( Price ),0)  AS Price                    -- prezzo medio ( valori nulli non considerati )
                        , COUNT (*)                 AS QtyTot                   -- N. Matrici nel gruppo
                        , COUNT ( CASE Active WHEN 0 THEN 1 END )   AS QtyEOL   -- Qta Matrici rottamate 
                        , ISNULL( AVG( ExpLife ), 0 )               AS ExpLife  -- Vita stimata matrice ( iniziale )
                        , ISNULL( AVG ( CASE WHEN Active = 0 AND ActLife > 5000 THEN ActLife END ),0 ) AS EOLLife   -- solo Matrici rottamate e vita > 5000KG
                FROM ext.DiesRaw
                GROUP BY CodDiesGroup
              ) AS Source
		ON Target.CodDiesGroup = Source.CodDiesGroup
		--WHEN MATCHED THEN
		--	UPDATE SET CodDiesGroup = Source.CodDiesGroup, Price = Source.Price, QtyTot = Source.QtyTot
  --                   , QtyEOL = Source.QtyEOL,  ExpLife = Source.ExpLife,  EOLLife = Source.EOLLife
  --                   , DateMod = GETDATE(), UserMod = 'IMPORT_DiesRaw'

		WHEN NOT MATCHED BY TARGET THEN
			INSERT ( CodDiesGroup, Price, QtyTot, QtyEOL, ExpLife, EOLLife, DateMod ,UserMod  )  
            VALUES ( CodDiesGroup, Source.Price, Source.QtyTot, Source.QtyEOL, Source.ExpLife, Source.EOLLife, GETDATE(), 'IMPORT_DiesRaw' ) -- mi da errori in calcoli successivi altrimenti con zero a ExpLife e EOLLife
		OUTPUT $action INTO @SummaryOfChanges;

        -- =======================================
		-- ora carico i dati delle singole matrici
        -- =======================================
		MERGE INTO DiesDet AS Target
		USING (SELECT CodDies, HoleNum, CodItem, CodDiesGroup, Price, ExpLife, ActLife, Active FROM ext.DiesRaw)
				AS Source
		ON Target.CodDies = Source.CodDies
		WHEN MATCHED THEN
			UPDATE SET HoleNum = Source.HoleNum, CodItem = Source.CodItem, CodDiesGroup = Source.CodDiesGroup, Price = Source.Price,  ExpLife = Source.ExpLife,  ActLife = Source.ActLife,  Active = Source.Active
		WHEN NOT MATCHED BY TARGET THEN
			INSERT (CodDies, HoleNum, CodItem, CodDiesGroup, Price, ExpLife, ActLife, Active)  VALUES (CodDies, HoleNum, CodItem, CodDiesGroup, Price, ExpLife, ActLife, Active) 
		OUTPUT $action INTO @SummaryOfChanges;

        -- =================================================
		-- Aggiorno i dati dei GRUPPI DI MATRICI ( DiesGroupDet )
        -- con tutti i dati presenti in dbo.DiesDet ( nel caso di aggiornamento parziale )
        -- =================================================
		MERGE INTO dbo.DiesGroupDet AS Target
		USING ( 
                SELECT    CodDiesGroup
                        , ISNULL ( AVG( Price ),0)  AS Price                    -- prezzo medio ( valori nulli non considerati )
                        , COUNT (*)                 AS QtyTot                   -- N. Matrici nel gruppo
                        , COUNT ( CASE Active WHEN 0 THEN 1 END )   AS QtyEOL   -- Qta Matrici rottamate 
                        , ISNULL( AVG( ExpLife ), 0 )               AS ExpLife  -- Vita stimata matrice ( iniziale )
                        , ISNULL( AVG ( CASE WHEN Active = 0 AND ActLife > 5000 THEN ActLife END ),0 ) AS EOLLife   -- solo Matrici rottamate e vita > 5000KG
                FROM dbo.DiesDet
                GROUP BY CodDiesGroup
              ) AS Source
		ON Target.CodDiesGroup = Source.CodDiesGroup
		WHEN MATCHED THEN
			UPDATE SET CodDiesGroup = Source.CodDiesGroup, Price = Source.Price, QtyTot = Source.QtyTot
                     , QtyEOL = Source.QtyEOL,  ExpLife = Source.ExpLife,  EOLLife = Source.EOLLife
                     , DateMod = GETDATE(), UserMod = 'UPDATE_DiesDet'

		WHEN NOT MATCHED BY TARGET THEN  -- nel caso siano mancanti
			INSERT ( CodDiesGroup, Price, QtyTot, QtyEOL, ExpLife, EOLLife, DateMod ,UserMod  )  
            VALUES ( CodDiesGroup, Source.Price, Source.QtyTot, Source.QtyEOL, Source.ExpLife, Source.EOLLife, GETDATE(), 'IMPORT_DiesDet' )
		OUTPUT $action INTO @SummaryOfChanges;

		---- a questo punto calcolo il VERO update dalle inforamzioni di dbo.DiesDet --> dbo.DiesGroupDet
		--MERGE INTO dbo.DiesGroupDet AS Target
		--USING  (
		--		SELECT coddiesgroup,
		--			   Avg(Isnull(price, 0)) AS Price,
		--			   Count(*) AS QtyTot,
		--			   Count(*) - Sum(Active) AS QtyEOL,
		--			   Avg(Isnull(ExpLife, 0.1)) AS ExpLife, -- mi da errori in calcoli successivi altrimenti con zero a ExpLife e EOLLife
		--			   Sum(Isnull(ActLife * (1 - Active), 0)) / (Count(*) - Sum(Active)) AS EOLLife
		--		FROM dbo.DiesDet
		--		WHERE ActLife > 5000
		--		GROUP BY CodDiesGroup
		--		HAVING	Count(*) > Sum(Active) -- ci siano rottamate
		--		)
		--		AS Source
		--ON Target.CodDiesGroup = Source.CodDiesGroup
		--WHEN MATCHED THEN
		--	UPDATE SET Price = Source.Price, QtyTot = Source.QtyTot, QtyEOL = Source.QtyEOL, ExpLife = Source.ExpLife,  EOLLife = Source.EOLLife
		--OUTPUT $action INTO @SummaryOfChanges;

	COMMIT tran
		
	-- Query the results of the table variable.
	SELECT Change, COUNT(*) AS CountPerChange
	FROM @SummaryOfChanges
	GROUP BY Change;
END
GO
PRINT N'Creating [ext].[stp_mergePlantsDet]...';


GO


-- =============================================
-- Author:		S.E. Locatelli
-- Create date: 2013.12.03
-- Description:	Procedura per import dati in PlantsDet da dati ProductionLogRaw
-- =============================================
CREATE PROCEDURE [ext].[stp_mergePlantsDet]
(
	@source NVARCHAR(20) = 'ProductionLogRaw' -- nome della tabella sorgente tra ProductionLogRaw e PackagRaw
)
AS
BEGIN
	SET NOCOUNT ON;
	
	-- Create a temporary table variable to hold the output actions.
	DECLARE @SummaryOfChanges TABLE(Change VARCHAR(20));

    -- import con MERGE... verifico tipo di caricamento richiesto!
	IF @source = 'ProductionLogRaw' -- carico da tracciato produzione
		BEGIN
			MERGE INTO PlantsDet AS Target
			USING (SELECT DISTINCT CodPlant FROM ext.ProductionLogRaw)
					AS Source
			ON Target.CodPlant = Source.CodPlant
			--WHEN MATCHED THEN
			--	UPDATE SET PackagName = Source.PackagName
			WHEN NOT MATCHED BY TARGET THEN
				INSERT (CodPlant, Descript) VALUES (CodPlant, 'Plant - ' + CodPlant)
			OUTPUT $action INTO @SummaryOfChanges;

		END
	--ELSE IF @source = 'PackagRaw' -- carico da anagrafica
	--	BEGIN
	--		MERGE INTO PackagDet AS Target
	--		USING (SELECT CodPackag, PackagDesc, RMCost, RMWeight, Tare, FullWeight FROM ext.PackagRaw)
	--				AS Source
	--		ON Target.CodPackag = Source.CodPackag
	--		WHEN MATCHED THEN
	--			UPDATE SET PackagDesc = Source.PackagDesc, RMCost = Source.RMCost, RMWeight = Source.RMWeight, Tare = Source.Tare,  FullWeight = Source.FullWeight
	--		WHEN NOT MATCHED BY TARGET THEN
	--			INSERT (CodPackag, PackagDesc, RMCost, RMWeight, Tare, FullWeight)  VALUES (CodPackag, PackagDesc, RMCost, RMWeight, Tare, FullWeight) 
	--		OUTPUT $action INTO @SummaryOfChanges;

	--	END
		
	-- Query the results of the table variable.
	SELECT Change, COUNT(*) AS CountPerChange
	FROM @SummaryOfChanges
	GROUP BY Change;
END
GO
PRINT N'Creating [ext].[stp_mergeOrdersHist]...';


GO

-- =============================================
-- Author:		Steamware
-- Mod. date:   2014.05.22
-- Description:	Procedura per import dati in OrdersHist da dati OrdersHistRaw
-- =============================================
CREATE PROCEDURE [ext].[stp_mergeOrdersHist]
(
    @source NVARCHAR(20) = 'OrdersHistRaw' -- nome della tabella sorgente
)
AS
BEGIN
    SET NOCOUNT ON;	

    -- Create a temporary table variable to hold the output actions.
    DECLARE @SummaryOfChanges TABLE(Change VARCHAR(20));
    
    -- import con MERGE... verifico tipo di caricamento richiesto!
    IF @source = 'OrdersHistRaw' -- carico da tracciato produzione
        BEGIN

            MERGE INTO dbo.OrdersHist AS Target
            USING( 
                   SELECT   OrdNum,
                            OrdRow,
                            OrdDate,
                            CodClient,
                            CodItem,
                            RawMat,
                            RawMatCost,
                            BatchQty,
                            CodInco,
                            OrdPrice,
                            RawMatExtraCost,
                            PriceOff,
                            OrdQty,
                            ProvvCost
                   FROM ext.OrdersHistRaw ) AS Source
            ON Target.Ordnum = Source.Ordnum AND Target.Ordrow = Source.Ordrow

            -- non faccio aggiornamento dei dati oppure potrei farlo solo per le righe non elaborate cioè con Codquote non valorizzato
            --WHEN MATCHED
            --THEN UPDATE SET
            --                Orddate     = Source.OrdDate,
            --                Codclient   = Source.CodClient,
            --                Coditem     = Source.CodItem,
            --                Rawmat      = Source.RawMat,
            --                Rawmatcost  = Source.RawMatCost,
            --                Batchqty    = Source.BatchQty,
            --                Codinco     = Source.CodInco,
            --                Ordprice    = Source.OrdPrice,
            --                Quotetype   = Source.QuoteType,
            --                Codquote    = Source.CodQuote,
            --                Quoterev    = Source.QuoteRev,
            --                Endcalc     = Source.EndCalc

            WHEN NOT MATCHED BY TARGET
            THEN INSERT (   OrdNum,
                            OrdRow,
                            OrdDate,
                            CodClient,
                            CodItem,
                            RawMat,
                            RawMatCost,
                            BatchQty,
                            CodInco,
                            OrdPrice,
                            RawMatExtraCost,
                            PriceOff,
                            OrdQty,
                            ProvvCost
                            --,Quotetype  
                            --,Codquote   
                            --,Quoterev   
                            --,Endcalc
                        )
            VALUES( OrdNum, OrdRow, OrdDate, CodClient, CodItem, RawMat, RawMatCost, BatchQty, CodInco, OrdPrice, RawMatExtraCost, PriceOff, OrdQty, ProvvCost ) -- , QuoteType, CodQuote, QuoteRev, EndCalc )
            OUTPUT $action INTO @SummaryOfChanges;
    END
    
    -- aggiorno indici tabella ( attenzione durata per tabelle grandi )
    ALTER INDEX ALL ON dbo.OrdersHist
    REBUILD WITH  ( FILLFACTOR = 100,  SORT_IN_TEMPDB = ON ) ; -- ,STATISTICS_NORECOMPUTE = ON ) 

    -- aggiorno statistiche tabella
    UPDATE STATISTICS dbo.OrdersHist WITH FULLSCAN;

    -- Query the results of the table variable.
    SELECT Change, COUNT(*) AS CountPerChange
    FROM @SummaryOfChanges
    GROUP BY Change;
END
GO
PRINT N'Creating [dbo].[stp_QuoteFull_Q_update]...';


GO
-- =============================================
-- Author:		Steamware
-- Create date: 2014.02.07
-- Description:	update valori tab QuoteList
-- =============================================
CREATE PROCEDURE [dbo].[stp_QuoteFull_Q_update] (
	@Original_QuoteType CHAR(1) = 'Q'
	,@Original_CodQuote BIGINT = 0
	,@Original_QuoteRev INT = 0
	,@PriceOff DECIMAL(9, 6) = 0
	)
AS
BEGIN

-- aggiorno valori!
	UPDATE QuoteList
	SET PriceOff = @PriceOff
	WHERE QuoteType = @Original_QuoteType
		AND CodQuote = @Original_CodQuote
		AND QuoteRev = @Original_QuoteRev

	-- update dei valori calcolati!
	EXEC stp_QL_fullDataUpdate @Original_QuoteType
		,@Original_CodQuote
		,@Original_QuoteRev
END
GO
PRINT N'Creating [dbo].[stp_test]...';


GO


CREATE PROCEDURE [dbo].[stp_test]
AS
    -- Test per funzionamento temp table
    SELECT TOP 1 * INTO #QuoteParam FROM dbo.ClientDet
    EXEC stp_QL_update 'Q', 1312130001, 0  --WITH RECOMPILE
    SELECT * FROM #QuoteParam
    DROP TABLE #QuoteParam
GO
PRINT N'Creating [dbo].[stp_QLF_UpdCosts]...';


GO

-- =============================================
-- Author:		Steamware - S.E.L.
-- Create date: 2014.04.15
-- Description:	update di un record in QL (Full) e poi aggiorna a cascata
-- =============================================
CREATE PROCEDURE [dbo].[stp_QLF_UpdCosts]
(
    @Original_QuoteType CHAR(1) = 'Q',
    @Original_CodQuote	BIGINT = 0,
    @Original_QuoteRev	INT = 0,
    @PriceOff			DECIMAL(18, 6)
)
AS

SET XACT_ABORT ON;
BEGIN TRAN

    -- aggiorno valori QuoteList!
    UPDATE QuoteList
    SET		PriceOff	= @PriceOff
    WHERE	QuoteType = @Original_QuoteType
        AND CodQuote = @Original_CodQuote
        AND QuoteRev = @Original_QuoteRev
        

    -- update dei valori calcolati!
    EXEC stp_QL_fullDataUpdate @Original_QuoteType
        ,@Original_CodQuote
        ,@Original_QuoteRev
        ,'Y'
        
COMMIT TRAN


-- seleziono intera riga!
    
SELECT	* 
FROM	v_QuoteFull_Q
WHERE	QuoteType = @Original_QuoteType
    AND CodQuote = @Original_CodQuote
    AND QuoteRev = @Original_QuoteRev


RETURN
GO
PRINT N'Creating [dbo].[stp_QLF_UpdHead]...';


GO

-- =============================================
-- Author:		Steamware - S.E.L.
-- Create date: 2014.04.11
-- Description:	update di un record in QL (Full) e poi aggiorna a cascata
-- =============================================
CREATE PROCEDURE [dbo].[stp_QLF_UpdHead]
(
    @Original_QuoteType CHAR(1) = 'Q',
    @Original_CodQuote	BIGINT = 0,
    @Original_QuoteRev	INT = 0,
    @CodClient			NVARCHAR(50) = '',
    @CodItem			NVARCHAR(50) = '',
    @RawMat				NVARCHAR(50),
    @RawMatCost			DECIMAL(18, 6),
    @RawMatExtraCost	DECIMAL(18, 6),
    @BatchQty			INT,
    @CodInco			NVARCHAR(5),
    @Note				NVARCHAR(2500) = ''
)
AS

SET XACT_ABORT ON;
BEGIN TRAN

    -- aggiorno valori QuoteList!
    UPDATE	ql
    SET		CodClient	= @CodClient
        ,	CodItem		= @CodItem
        ,	RawMat		= @RawMat
        ,	BatchQty	= @BatchQty
        ,	CodInco		= @CodInco
        ,	Note		= @Note
		,	CodItemGroup= id.CodItemGroup
		,	UnitWeight	= id.UnitWeight
	FROM	QuoteList ql
		INNER JOIN ItemDet id ON id.CodItem	= @CodItem
	WHERE	ql.QuoteType = @Original_QuoteType
        AND ql.CodQuote = @Original_CodQuote
        AND ql.QuoteRev = @Original_QuoteRev
        
    -- aggiorno valori QuoteRM
    UPDATE QuoteRM
    SET		RawMat		= @RawMat
        ,	RawMatCost	= @RawMatCost
        ,	RawMatExtraCost	= @RawMatExtraCost
    WHERE	QuoteType = @Original_QuoteType
        AND CodQuote = @Original_CodQuote
        AND QuoteRev = @Original_QuoteRev

    -- update dei valori calcolati!
    EXEC stp_QL_fullDataUpdate @Original_QuoteType
        ,@Original_CodQuote
        ,@Original_QuoteRev
        ,'Y'
        
COMMIT TRAN


-- seleziono intera riga!
    
SELECT	* 
FROM	v_QuoteFull_Q
WHERE	QuoteType = @Original_QuoteType
    AND CodQuote = @Original_CodQuote
    AND QuoteRev = @Original_QuoteRev


RETURN
GO
PRINT N'Creating [dbo].[stp_QLF_UpdQState]...';


GO

-- =============================================
-- Author:		Steamware - S.E.L.
-- Create date: 2014.04.16
-- Description:	update di un record in QL (Full) e poi aggiorna a cascata
-- =============================================
CREATE PROCEDURE [dbo].[stp_QLF_UpdQState]
(
    @Original_QuoteType CHAR(1) = 'Q',
    @Original_CodQuote	BIGINT = 0,
    @Original_QuoteRev	INT = 0,
    @IdxQState			INT
)
AS

SET XACT_ABORT ON;
BEGIN TRAN

    -- aggiorno valori QuoteList!
    UPDATE QuoteList
    SET		IdxQState	= @IdxQState
    WHERE	QuoteType = @Original_QuoteType
        AND CodQuote = @Original_CodQuote
        AND QuoteRev = @Original_QuoteRev
        

    -- update dei valori calcolati!
    EXEC stp_QL_fullDataUpdate @Original_QuoteType
        ,@Original_CodQuote
        ,@Original_QuoteRev
        ,'Y'
        
COMMIT TRAN


-- seleziono intera riga!
    
SELECT	* 
FROM	v_QuoteFull_Q
WHERE	QuoteType = @Original_QuoteType
    AND CodQuote = @Original_CodQuote
    AND QuoteRev = @Original_QuoteRev


RETURN
GO
PRINT N'Creating [dbo].[stp_zzz_scratch]...';


GO






-- =============================================
-- Author:		S.E. Locatelli
-- Create date: 2013.11.20
-- Description:	Procedure x calcoli e test import dati e prove varie
-- =============================================
CREATE PROCEDURE [dbo].[stp_zzz_scratch] 
AS
BEGIN
	
    -- dichiaro e imposto periodo di calcolo dei valori
    -- andrà impostato in una tabella e mi determinerà la versione dei dati
    DECLARE @dateFrom AS DateTime;
    DECLARE @dateTo   AS DateTime;

    SET @dateFrom = '20100101' 
    SET @dateTo   = '20130929'

    -- ==========================================
    -- IMPORTAZIONE DATI CSV
    -- ==========================================
    exec tmp.importProductionLogRaw
	exec tmp.importClientsRaw
	exec tmp.importTranspCostRaw
	exec tmp.importItemsRaw
	exec tmp.importPackagRaw
	exec tmp.importDiesRaw
    -- questo sotto va fatto solo se ci sono dati da integrare in DiesRaw
	exec tmp.importDiesGroupRaw

	select top 10 *  FROM tmp.ProductionLogRaw
	select *  FROM tmp.ClientsRaw
	select *  FROM tmp.ItemsRaw
	select *  FROM tmp.PackagRaw
	select *  FROM tmp.DiesRaw
	select *  FROM tmp.DiesGroupRaw

    -- Se ci sono record con Item doppi li cancello????
	SELECT CodItem,COUNT(*) as qty
	FROM ( SELECT DISTINCT * FROM tmp.ItemsRaw ) AS a
	GROUP BY  CodItem
	having COUNT(*)>1

	delete from tmp.ItemsRaw
	where CodItem IN
	(
	    SELECT CodItem
	    FROM ( SELECT DISTINCT * FROM tmp.ItemsRaw ) AS a
	    GROUP BY CodItem
	    having COUNT(*)>1
	)
	

    -- ==========================================
    -- CARICO DATI IN RAW ( da Char a Tipi corretti )
    -- ==========================================	
	exec tmp.convertClientsRaw
	exec tmp.convertTranspCostRaw
	exec tmp.convertItemsRaw
	exec tmp.convertProductionLogRaw
	exec tmp.convertPackagRaw
	exec tmp.convertDiesRaw

	-- necessario se integriamo i dati x i gruppi di matrici con un file
	exec tmp.convertDiesGroupRaw

	select top 10 *  FROM ext.ProductionLogRaw
	select *  FROM ext.ClientsRaw
	select *  FROM ext.ItemsRaw
	select *  FROM ext.PackagRaw
	select *  FROM ext.DiesRaw
    SELECT *  FROM ext.DiesGroupRaw

	-- elimino a mano dato con oltre 68 anni di evento...
	select * 
	--delete
	from ext.ProductionLogRaw
	where DATEDIFF(YEAR,EventStart,EventEnd)> 10

	exec ext.stp_mergeAgentsDet
	exec ext.stp_mergeClientDet     'ProductionLogRaw'
	exec ext.stp_mergeClientDet     'ClientsRaw'
	exec ext.stp_mergeTranspCostDet 'TranspCostRaw'
	exec ext.stp_mergePlantsDet
	exec ext.stp_mergeCost2Plant
	exec ext.stp_mergeItemDet               'ItemsRaw'
	exec ext.stp_mergePackagDet             'ProductionLogRaw'                      -- 'PackagRaw'
    
    -- QUESTE ANDREBBERO ESEGUITO DOPO ext.stp_updateProductionLog prendendo in considerazione un periodo di tempo
    -- di tre anno o comunque stabilito a priori predefinito ( configurabile a sistema )
    -- DA VERIFICARE
	exec ext.stp_mergePackage2ItemClient    'ProductionLog', @dateFrom, @dateTo
	exec ext.stp_mergePackage2Item          'ProductionLog', @dateFrom, @dateTo
	exec ext.stp_mergePackage2              'ProductionLog', @dateFrom, @dateTo

	exec ext.stp_mergeDiesDet
	-- se ricarico diesgroup... ricarico solo i campi che nel file sono <> ''
	exec ext.stp_mergeDiesGroupDet

	exec ext.stp_mergeRawMat
	exec ext.stp_updateProductionLog

	---- aggiorno quota agenti a 0.037
	----update AgentsDet set quotaperc=0.0374


	SELECT DISTINCT dr.CodItem FROM ext.DiesRaw dr LEFT OUTER JOIN ItemDet id ON dr.CodItem = id.CodItem
	where id.CodItemGroup is null

	select * from ClientDet
	select * from ItemDet
	select * from Package2ItemClient
	select * from Package2Item
	select * from Package2
	select * from PackagDet
	select * from DiesGroupDet where EOLLife > 0
	select * from DiesDet
	select * from DiesGroupDet
	select * from AgentsDet
	select * from PlantsDet
	select * from Cost2Plant
	select * from utilities
	select top 100 * from ProductionLog

	--update tmp.ProductionLogRaw
	--set
	--	okPr = 1
	--	, okDi = 1
	--	, okQM = 1
	--	, okSc = 1
	
	select distinct ProcessNum from ProductionLog

	select top 10 * from ext.ProductionLogRaw


	---- fix errore packaging
	--update tmp.ProductionLogRaw 
	--SET CodPackag='4'
	--where CodPackag LIKE '%4%' and CodPackag <> '4'
	--select * from tmp.ProductionLogRaw where CodPackag LIKE '%4%' and CodPackag <> '4'

	SELECT p.CodDies, CodItem, CodClient, CodPackag, p.* FROM ext.ProductionLogRaw AS p
	LEFT JOIN dbo.DiesDet AS d ON p.CodDies = d.CodDies 
	WHERE CodItem IS NULL



	-- parte CALCOLI!!!

	select * from QuoteList

	select * from ClientDet where CodClient='05000001048'

	select * from itemdet
	where CodItem like '1PT00102%'

	select * from RawMatDet


	--Q	1312130001	0	05000001048	1PT00102	A	7020	7673,400	1000	CPT	NULL	NULL	NULL	NULL

	SELECT	--TOP 10 
			 dd.CodItem, pl.RawMat, dd.CodItem + '-' + pl.RawMat as KeyAM, dd.CodDiesGroup, pl.CodPlant, dd.HoleNum
			,dd.CodItem + '-' + pl.RawMat + '-' + pl.CodPlant + '-' + CAST(dd.HoleNum AS NVARCHAR(19)) as KeyAMIL
			,0 as NumSMED -- numero cambi, da sistemare...
			, SUM(QtyOUT) as KgTeorici, SUM(Duration) AS Durata
			,ISNULL(SUM(QtyOUT),0)/ISNULL(SUM(Duration), 1) as ProduttTeo
	FROM	ProductionLog pl INNER JOIN DiesDet dd ON pl.CodDies=dd.CodDies
	WHERE	pl.ProcessNum='01' and pl.EventType=1
	GROUP BY dd.CodItem, pl.RawMat, dd.CodDiesGroup, pl.CodPlant, dd.HoleNum
	ORDER BY dd.CodItem, pl.RawMat, dd.CodDiesGroup, SUM(QtyOUT) DESC

    -- ==========================================
	-- re-insert dei dati di produzione x statistiche
    -- ==========================================
	exec stp_TPS_upsert @dateFrom, @dateTo
	exec stp_TD_upsert @dateFrom , @dateTo
--	exec stp_TI_upsert @dateFrom , @dateTo   -- adesso sono già calcolati e inseriti in Package2 / Package2Item

    -- ==========================================
	-- salvo nuova revisione dati di produzione...
    -- Va messa in ogni procedura di update con 'procedura' e versione anno-mese-giorno
    -- ==========================================
	INSERT INTO RevHistory
	SELECT	'P', ISNULL(MAX(RevNum),0) + 1, GETDATE(), 'Aggiornamento dati di produzione x fase 04 ' + CONVERT(NVARCHAR(20), @dateFrom, 120) + ' --> ' +CONVERT(NVARCHAR(20), @dateTo, 120)
	FROM	RevHistory
	WHERE	RevType = 'P'


	select * from RevHistory

	-- simulazione tempo di calcolo: circa 50/sec
	---- aggiornamento dei dati dell'offerta in oggetto
	--DECLARE @tick DATETIME,
	--		@idx INT = 100
	--SET @tick = GETDATE()
	--WHILE @idx > 0
	--BEGIN
	--	EXEC stp_QL_update 'Q', 1312130001, 0
	--	SELECT @idx = @idx - 1
	--END
	--SELECT GETDATE() - @tick as tempo
	
	DECLARE @QuoteType	CHAR(1) = 'Q',
			@CodQuote	BIGINT	= 1312130001,
			@QuoteRev	INT		= 0

	EXEC stp_QL_update @QuoteType, @CodQuote, @QuoteRev
	SELECT	* FROM	QuoteList    WHERE QuoteType=@QuoteType AND CodQuote = @CodQuote AND  QuoteRev = @QuoteRev
	SELECT	* FROM	QuoteRM      WHERE QuoteType=@QuoteType AND CodQuote = @CodQuote AND  QuoteRev = @QuoteRev
	SELECT	* FROM	QuoteWorkInt WHERE QuoteType=@QuoteType AND CodQuote = @CodQuote AND  QuoteRev = @QuoteRev
	SELECT	* FROM	QuoteWorkExt WHERE QuoteType=@QuoteType AND CodQuote = @CodQuote AND  QuoteRev = @QuoteRev
	SELECT	* FROM	QuoteOC      WHERE QuoteType=@QuoteType AND CodQuote = @CodQuote AND  QuoteRev = @QuoteRev
	SELECT	* FROM	QuoteParam   WHERE QuoteType=@QuoteType AND CodQuote = @CodQuote AND  QuoteRev = @QuoteRev

	select top 10 * from ItemDet

	SELECT	* FROM	RawMatDet
	
	SELECT	top 10	* FROM TabProdSc
	SELECT	top 10	* FROM TabDifett
--	SELECT			* FROM TabImbArt
--	SELECT			* FROM TabImbGrp
	SELECT			* FROM PackagDet
	SELECT			* FROM Package2

	---- test gestione selezione CodPackag corretto
	--SELECT TOP 5 * FROM Package2ItemClient
	--SELECT TOP 5 * FROM Package2Item
	--SELECT TOP 5 * FROM Package2

	SELECT dbo.f_getCodPackag('1EL00005', '05000001048')
	--SELECT dbo.f_getCodPackag('1AN00001', '05000000137')
	
	
	
END
GO
PRINT N'Creating [dbo].[stp_QL_insNew]...';


GO

-- =============================================
-- Author:		Steamware
-- Create date: 2014.02.21
-- Description:	inserisce un nuovo record QuoteList
-- =============================================
CREATE PROCEDURE [dbo].[stp_QL_insNew]
(
    @QuoteType			CHAR(1) = 'Q',
    @CodClient			NVARCHAR(50) = '',
    @CodItem			NVARCHAR(50) = '',
    @RawMat				NVARCHAR(50),
    @RawMatCost			DECIMAL(18, 6),
    @RawMatExtraCost	DECIMAL(18, 6),
    @BatchQty			INT,
    @CodInco			NVARCHAR(5),
    @Note				NVARCHAR(2500)
)
AS

-- variabili
DECLARE	@CodQuote		BIGINT	= 0,
        @QuoteRev		INT		= 0

SET XACT_ABORT ON;
BEGIN TRAN

    -- calcolo nuovo record odierno
    SELECT	@CodQuote = dbo.f_getNewCodQuote()

    -- inserisco riga in QuoteList
    INSERT INTO QuoteList(QuoteType, CodQuote, QuoteRev, CodClient, CodItem, UnitWeight, BatchQty, CodItemGroup, RawMat, CodInco, Note)
    SELECT      @QuoteType, @CodQuote, @QuoteRev, @CodClient, CodItem, UnitWeight, @BatchQty, CodItemGroup, @RawMat, @CodInco, @Note
    FROM        ItemDet
    WHERE       CodItem = @CodItem

    -- ora inserisco in QuoteRM
    INSERT INTO QuoteRM(QuoteType, CodQuote, QuoteRev, NumRM, RawMat, RawMatCost, RawMatExtraCost)
    VALUES      (@QuoteType, @CodQuote, @QuoteRev, 1, @RawMat, @RawMatCost, @RawMatExtraCost)
    
    -- ricalcolo!
    EXEC stp_QL_fullDataUpdate @QuoteType
            , @CodQuote
            , @QuoteRev
            , 'N'

COMMIT TRAN

-- seleziono intera riga!
SELECT	* 
FROM	QuoteList
WHERE	QuoteType = @QuoteType
    AND	CodQuote = @CodQuote
    AND	QuoteRev = @QuoteRev

RETURN
GO
PRINT N'Creating [dbo].[stp_QLS_UpdDiesPar]...';


GO

-- =============================================
-- Author:		Steamware - S.E.L.
-- Create date: 2014.05.20
-- Description:	update di un record in QL (Full) TIPO SIMULAZIONE e poi aggiorna a cascata
-- =============================================
CREATE PROCEDURE [dbo].[stp_QLS_UpdDiesPar]
(
    @Original_QuoteType CHAR(1) = 'S',
    @Original_CodQuote	BIGINT = 0,
    @Original_QuoteRev	INT = 0,
    @SamplePrice        DECIMAL(18, 6),
    @DiesPriceClientQuote   DECIMAL(18, 6),
    @DiesCommLife       DECIMAL(18, 6),
    @MonthSalesPrev     INT
)
AS

SET XACT_ABORT ON;
BEGIN TRAN

    -- @SamplePrice
    EXEC stp_QSP_upsert @Original_QuoteType, @Original_CodQuote, @Original_QuoteRev, 'SamplePrice', @SamplePrice
    
    -- @DiesPriceClientQuote
    EXEC stp_QSP_upsert @Original_QuoteType, @Original_CodQuote, @Original_QuoteRev, 'DiesPriceClientQuote', @DiesPriceClientQuote
    
    -- @DiesCommLife
    EXEC stp_QSP_upsert @Original_QuoteType, @Original_CodQuote, @Original_QuoteRev, 'DiesCommLife', @DiesCommLife
    
    -- @MonthSalesPrev
    EXEC stp_QSP_upsert @Original_QuoteType, @Original_CodQuote, @Original_QuoteRev, 'MonthSalesPrev', @MonthSalesPrev
    
   
    -- update dei valori calcolati!
    EXEC stp_QL_fullDataUpdate @Original_QuoteType
        ,@Original_CodQuote
        ,@Original_QuoteRev
        ,'Y'
        
COMMIT TRAN


-- seleziono intera riga!
    
SELECT	* 
FROM	v_QuoteFull_Q
WHERE	QuoteType = @Original_QuoteType
    AND CodQuote = @Original_CodQuote
    AND QuoteRev = @Original_QuoteRev


RETURN
GO
PRINT N'Creating [dbo].[stp_SC2C_insertForDate]...';


GO

-- =============================================
-- Author:		Steamware
-- Mod. date:   2014.05.29
-- Description:	creazione dati base per Cost List per data odierna
-- =============================================
CREATE PROCEDURE [dbo].[stp_SC2C_insertForDate]
	@RawMatCost DECIMAL(18,6)   = 2,
	@BatchQty   INT             = 1000
AS
BEGIN

DECLARE @Date AS SMALLDATETIME = CONVERT( SMALLDATETIME,CONVERT(CHAR(8), GETDATE(), 112) ) ;

-- ===========================================================
-- se non esiste, CREO DATI LISTINO COSTI per il giorno
-- ===========================================================
IF NOT EXISTS( SELECT * FROM dbo.CostList WHERE QuoteType = 'C' AND DateList = @Date )
	BEGIN
		INSERT INTO dbo.CostList WITH (TABLOCK) ( DateList,CodItem,RawMat,RawMatCost,RawMatExtraCost,batchQty,CodInco )
		EXEC dbo.stp_QFC_creaListino @RawmatCost , @BatchQty

        -- aggiorno statistiche tabella
        UPDATE STATISTICS dbo.CostList WITH FULLSCAN;
	END

RETURN

END
GO
PRINT N'Creating [dbo].[stp_QLC_insNew]...';


GO
-- =============================================
-- Author:		Steamware
-- Mod. date:   2014.05.26
-- Description:	elaborazione dbo.QuoteFull_C ( listino )
-- =============================================
CREATE PROCEDURE [dbo].[stp_QLC_insNew]
(
	@row2proc   INT             = 100,
	@Note		NVARCHAR(2500)  = '',
	@QuoteType	CHAR(1)         = 'C'  -- per il momento è fisso = 'C'
)
AS
BEGIN 

SET NOCOUNT ON;

-- declare variabili
DECLARE	@CodQuote	        AS BIGINT,
		@QuoteRev	        AS INT	= 0,
		@OrdNum             AS NVARCHAR(50),
		@OrdRow             AS NVARCHAR(50),
		@CodItem            AS NVARCHAR(50),
		@CodClient          AS NVARCHAR(50)  = '',
		@RawMat             AS NVARCHAR(50),
		@RawMatCost         AS DECIMAL(18,6) = 0,
		@BatchQty           AS INT           = 0,
		@RawMatExtraCost    AS DECIMAL(18,6),
		@CodInco            AS NVARCHAR(5),
		@PriceOff           AS DECIMAL(9,6),
		@OrdDate            As DATETIME,
		@OrdPrice           AS DECIMAL(9,6),
		@OrdQty             AS INT,
		@oggi               AS DATETIME = GETDATE(),
		@LastIdx            AS INT,
		@noRow              AS CHAR(1)  = 'N',
		@TotRow             AS INT      = 0,
		@Date               AS SMALLDATETIME = CONVERT(SMALLDATETIME,CONVERT(CHAR(8), GETDATE(), 112))
			
SET XACT_ABORT ON;

SET @QuoteType = 'C'  -- per il momento non lascio parametrico il quotetype = C - Costi

-- se non esiste il contatore creo il record contatore
IF NOT EXISTS ( SELECT * FROM dbo.ContatoriQuote WHERE Flusso = @QuoteType )
	INSERT INTO dbo.ContatoriQuote SELECT @QuoteType, 0

/* viene fatta da altra stored
-- ===========================================================
-- se non esiste, CREO LISTINO per il giorno carico listino
-- ===========================================================
IF NOT EXISTS( SELECT * FROM dbo.CostList 
			   WHERE QuoteType = @QuoteType AND DateList = @Date )
					 -- AND LEFT(CodQuote,6) = CONVERT( BIGINT, ( RIGHT(YEAR(@oggi),2) + dbo.f_padLeft(MONTH(@oggi), 2,'0') + dbo.f_padLeft(DAY(@oggi), 2,'0') ) ) )
	BEGIN
		INSERT INTO dbo.CostList WITH (TABLOCK) ( DateList,CodItem,RawMat,RawMatCost,RawMatExtraCost,batchQty,CodInco )
		EXEC dbo.stp_QFC_creaListino @RawmatCost , @BatchQty
	END
*/

-- verifico se ci sono record da elaborare
IF EXISTS ( SELECT * FROM dbo.CostList WHERE QuoteType = @QuoteType AND CodQuote = 0 ) 
   SET @noRow = 'N'

WHILE( @noRow = 'N' AND @row2proc > 0)
BEGIN
	-- ===========================================================
	-- stacco il CodQuote da usare e sbocco la tabella ( in realtà perdo un numero se poi non faccio insert )
	-- se non eseguo procedure multiple contemporanee non serve 
	-- ===========================================================
	DECLARE @Table TABLE ( LastIdx INT ) 
	BEGIN TRAN;
			UPDATE dbo.ContatoriQuote
				SET LastIdx = ( LastIdx % 1000000 ) + 1   -- si resetta dopo 1.000.000 righe ( in pratica ho tot righe al giorno )
			OUTPUT inserted.LastIdx INTO @Table
			WHERE Flusso = @QuoteType
		
			SELECT @LastIdx  = MAX(LastIdx) FROM @Table
			SELECT @CodQuote = CONVERT( BIGINT, ( RIGHT(YEAR(@oggi),2) + dbo.f_padLeft(MONTH(@oggi), 2,'0') + dbo.f_padLeft(DAY(@oggi), 2,'0') + dbo.f_padLeft(@LastIdx, 8,'0') ) )
	COMMIT;


	-- ===========================================================
	-- elaboro il primo ordine "libero" assegnando il CodQuote
	-- se da errore la transazione mi annulla il codquote e quindi rimane elaborabile
	-- altrimenti metto l'assegnazione nella tran precedente e poi decido cosa fare con quelli non completati con data EndCalc = NULL
	-- ===========================================================
	-- SET TRANSACTION ISOLATION LEVEL REPEATABLE READ; -- SERIALIZABLE; -- REPEATABLE READ;
	BEGIN TRANSACTION;

		-- leggo il primo record da elaborare e assegno il CodQuote
		WITH cteFree AS 
		(   -- leggo il primo ordine da elaborare e assegno il CodQuote
			SELECT TOP(1) CodItem, RawMat FROM dbo.CostList WHERE DateList = @Date AND QuoteType = @QuoteType AND CodQuote = 0
		)
		UPDATE dbo.CostList
			SET CodQuote     = @CodQuote,
				QuoteType    = @QuoteType
		FROM dbo.CostList  AS ls
		INNER JOIN cteFree AS cte 
		ON ls.DateList = @Date AND ls.CodItem = cte.CodItem AND ls.RawMat = cte.RawMat
--        OPTION (RECOMPILE)

		-- leggo i valori di calcolo 
		SET @CodItem = NULL
		SELECT  @CodItem            = CodItem,
				@BatchQty           = batchQty,
				@RawMat             = RawMat,
				@RawMatCost         = RawMatCost,
				@RawMatExtraCost    = RawMatExtraCost,
				@CodInco            = CodInco
		FROM dbo.CostList 
		WHERE QuoteType = @QuoteType AND CodQuote = @CodQuote
		OPTION (RECOMPILE);

        -- imposto il Cliente a non specificato ( CUSTOMER ND )
        SET @CodClient = '00000000000'

		IF @CodItem IS NOT NULL
			BEGIN

				-- -------------------------------------------------------
				-- inserisco dati per elaborazione in QuoteList e QuoteRM
				-- -------------------------------------------------------
				INSERT INTO dbo.QuoteList( QuoteType, CodQuote, QuoteRev, CodClient, CodItem, UnitWeight, BatchQty, CodItemGroup, RawMat, CodInco, Note )
				SELECT      @QuoteType, @CodQuote, @QuoteRev, @CodClient, CodItem, UnitWeight, @BatchQty, CodItemGroup, @RawMat, @CodInco, @Note
				FROM        dbo.ItemDet
				WHERE       CodItem = @CodItem

				INSERT INTO dbo.QuoteRM(QuoteType, CodQuote, QuoteRev, NumRM, RawMat, RawMatCost, RawMatExtraCost)
				VALUES      (@QuoteType, @CodQuote, @QuoteRev, 1, @RawMat, @RawMatCost, @RawMatExtraCost)
	
				-- -------------------------------------------------------
				-- ricalcolo!
				-- -------------------------------------------------------
				EXEC dbo.stp_QL_fullDataUpdate @QuoteType , @CodQuote , @QuoteRev, 'Y';

				-- aggiorno data-ora fine elaborazione
				UPDATE dbo.CostList
					SET EndCalc = GETDATE()
				WHERE QuoteType = @QuoteType AND CodQuote = @CodQuote

				--SELECT * FROM dbo.QuoteList WHERE QuoteType = 'C' AND CodQuote = @CodQuote
				--SELECT * FROM dbo.QuoteRM WHERE QuoteType = 'C' AND CodQuote = @CodQuote 
				--SELECT TOP(1000) * FROM dbo.QuoteFull_C WHERE QuoteType = 'C' AND CodQuote = @CodQuote 
			END
		ELSE
			SET @noRow = 'Y'   -- fine righe da elaborare

	COMMIT TRAN
	SET @row2proc = @row2proc - 1

/*
		SET @TotRow = @TotRow -1 -- decremento righe da leggere

	COMMIT TRAN;
	END TRY
	BEGIN CATCH
		SELECT  'Error'
				,@CodItem
				,@CodClient          
				,@BatchQty           
				,@RawMat             
				,@RawMatCost         
				,@RawMatExtraCost    
				,@CodInco            
				, @TotRow
--        ROLLBACK

	 DECLARE @ErrorMessage NVARCHAR(4000);
	 DECLARE @ErrorSeverity INT;
	 DECLARE @ErrorState INT;

	SELECT    @ErrorMessage  = ERROR_MESSAGE() + ' Error Number: ' + CONVERT( Varchar(10) , ERROR_NUMBER())
											 + ' Severity: ' + CONVERT( Varchar(10) , ERROR_SEVERITY() ) + ' : '
											 + ISNULL(ERROR_PROCEDURE(),'stored?') 
											 + ' Line: ' + CONVERT(VARCHAR(100),ERROR_LINE()),

			@ErrorSeverity  = 8, -- ERROR_SEVERITY(),
			@ErrorState     = ERROR_STATE();

	RAISERROR (@ErrorMessage,  -- Message text.
			   @ErrorSeverity, -- Severity.
			   @ErrorState     -- State.
			   );

		SET @TotRow = @TotRow -1 -- decremento righe da leggere
	END CATCH
*/

END                 -- END WHILE

RETURN
END

/*
-- Pulizia Tabelle di appoggio x QuoteType = 'C'

TRUNCATE TABLE CostList
DELETE FROM dbo.QuoteOC      WHERE QuoteType = 'C'
DELETE FROM dbo.QuoteParam   WHERE QuoteType = 'C'
DELETE FROM dbo.QuoteWorkExt WHERE QuoteType = 'C'
DELETE FROM dbo.QuoteWorkInt WHERE QuoteType = 'C'
DELETE FROM dbo.QuoteRM      WHERE QuoteType = 'C'
DELETE FROM dbo.QuoteList    WHERE QuoteType = 'C'

SELECT TOP 1000 * FROM dbo.QuoteList    WHERE QuoteType = 'C'  -- AND CodQuote = '14052600000001'
SELECT * FROM dbo.QuoteRM WHERE QuoteType = 'C'                -- AND CodQuote = '14052600000001'
SELECT TOP 1000 * FROM dbo.QuoteOC      WHERE QuoteType = 'C'  -- AND CodQuote = '14052600000002'
SELECT TOP 1000 * FROM dbo.QuoteParam   WHERE QuoteType = 'C'  -- AND CodQuote = '14052600000993'
SELECT TOP 1000 * FROM dbo.QuoteWorkInt WHERE QuoteType = 'C'  -- AND CodQuote = '14052600000993'

SELECT * FROM CostList
SELECT * FROM dbo.QuoteFull_C WHERE QuoteType = 'C' 

SELECT TOP 1000 * FROM ItemDet WHERE CodItem = '1BQ00012' 

-- RIPULISCO TUTTO 
TRUNCATE TABLE dbo.QuoteFull_C

UPDATE dbo.ContatoriQuote
SET LastIdx = 0 WHERE Flusso = 'C'

*/
GO
PRINT N'Creating [dbo].[stp_QLC_insNew_OLD]...';


GO
-- =============================================
-- Author:		Steamware
-- Mod. date:   2014.05.26
-- Description:	elaborazione dbo.QuoteFull_C ( listino )
-- =============================================
CREATE PROCEDURE [dbo].[stp_QLC_insNew_OLD]
(
	@RawMatCost DECIMAL(18,6)   = 2,
	@BatchQty   INT             = 1000,
	@QuoteType	CHAR(1)         = 'C',  -- non usato al momento
	@Note		NVARCHAR(2500)  = '',
	@row2proc   INT             = 100
)
AS

SET NOCOUNT ON;

-- declare variabili
DECLARE	@CodQuote	        AS BIGINT,
		@QuoteRev	        AS INT	= 0,
		@OrdNum             AS NVARCHAR(50),
		@OrdRow             AS NVARCHAR(50),
		@CodItem            AS NVARCHAR(50),
		@CodClient          AS NVARCHAR(50),
		@RawMat             AS NVARCHAR(50),
		@RawMatExtraCost    AS DECIMAL(18,6),
		@CodInco            AS NVARCHAR(5),
		@PriceOff           AS DECIMAL(9,6),
		@OrdDate            As DATETIME,
		@OrdPrice           AS DECIMAL(9,6),
		@OrdQty             AS INT,
		@oggi               AS DATETIME = GETDATE(),
		@LastIdx            AS INT,
		@noRow              AS CHAR(1)  = 'N',
		@TotRow             AS INT      = 0
			
SET XACT_ABORT ON;

SET @QuoteType = 'C'  -- per il momento non lascio parametrico il quotetype = C - Costi

-- se non esiste il contatore creo il record
IF NOT EXISTS ( SELECT * FROM dbo.ContatoriQuote WHERE Flusso = @QuoteType )
	INSERT INTO  dbo.ContatoriQuote SELECT @QuoteType, 0

-- creo il listino da elaborare
CREATE TABLE #temp (
					[IdxRiga]           [int] IDENTITY(1,1),
--	                [DataRif]           [datetime] NOT NULL,     -- CodQuote ha già la data
--					[QuoteType]         [char](1) NOT NULL,
--					[CodClient]         [nvarchar](50) NOT NULL,
					[CodItem]           [nvarchar](50) NOT NULL,
					[RawMat]            [nvarchar](50) NOT NULL,
					[RawMatCost]        [decimal](18, 6) NULL,
					[RawMatExtraCost]   [decimal](18, 6) NULL,
					[batchQty]          [int] NULL,
					[CodInco]           [nvarchar](5) NOT NULL

  PRIMARY KEY ( [IdxRiga] ) WITH (PAD_INDEX  = ON, FILLFACTOR = 100)
) ON [PRIMARY]

INSERT INTO #temp ( CodItem,RawMat,RawMatCost,RawMatExtraCost,batchQty,CodInco )
EXEC dbo.stp_QFC_creaListino @RawmatCost , @BatchQty

SET @TotRow = @@ROWCOUNT  -- metto via record da elaborare

SELECT @TotRow 
-- SELECT @TotRow = COUNT(*) FROM #temp WHERE QuoteType = @QuoteType

-- SET @TotRow = 100 -- elaboro solo 1000 x test

SELECT TOP 100 * FROM #temp ORDER BY [IdxRiga] DESC

WHILE( @TotRow > 0 )
BEGIN
	-- ===========================================================
	-- stacco il CodQuote da usare e sbocco la tabella ( in realtà perdo un numero se poi non faccio insert )
	-- se non eseguo procedure multiple contemporanee non serve 
	-- ===========================================================
	DECLARE @Table TABLE ( LastIdx INT ) 
	BEGIN TRAN;
			UPDATE dbo.ContatoriQuote
				SET LastIdx = ( LastIdx % 1000000 ) + 1   -- si resetta dopo 1.000.000 righe ( in pratica ho tot righe al giorno )
			OUTPUT inserted.LastIdx INTO @Table
			WHERE Flusso = @QuoteType
		
			SELECT @LastIdx  = MAX(LastIdx) FROM @Table
			SELECT @CodQuote = CONVERT( BIGINT, ( RIGHT(YEAR(@oggi),2) + dbo.f_padLeft(MONTH(@oggi), 2,'0') + dbo.f_padLeft(DAY(@oggi), 2,'0') + dbo.f_padLeft(@LastIdx, 8,'0') ) )
	COMMIT;

	-- ===========================================================
	-- elaboro il record in sequenza
	-- ===========================================================
	-- SET TRANSACTION ISOLATION LEVEL REPEATABLE READ; -- SERIALIZABLE; -- REPEATABLE READ;
	BEGIN TRY
--     BEGIN TRANSACTION;

		-- leggo i valori di calcolo 
		SELECT  @CodItem            = CodItem,
				@BatchQty           = batchQty,
				@RawMat             = RawMat,
				@RawMatCost         = RawMatCost,
				@RawMatExtraCost    = RawMatExtraCost,
				@CodInco            = CodInco
		FROM #temp
		WHERE IdxRiga = @TotRow

		IF @CodItem IS NOT NULL
			BEGIN

				-- -------------------------------------------------------
				-- inserisco dati per elaborazione in QuoteList e QuoteRM
				-- -------------------------------------------------------
				INSERT INTO dbo.QuoteList( QuoteType, CodQuote, QuoteRev, CodClient, CodItem, UnitWeight, BatchQty, CodItemGroup, RawMat, CodInco, Note )
				SELECT      @QuoteType, @CodQuote, @QuoteRev, @CodClient, CodItem, UnitWeight, @BatchQty, CodItemGroup, @RawMat, @CodInco, @Note
				FROM        dbo.ItemDet
				WHERE       CodItem = @CodItem

				INSERT INTO dbo.QuoteRM(QuoteType, CodQuote, QuoteRev, NumRM, RawMat, RawMatCost, RawMatExtraCost)
				VALUES      (@QuoteType, @CodQuote, @QuoteRev, 1, @RawMat, @RawMatCost, @RawMatExtraCost)
	
				-- -------------------------------------------------------
				-- ricalcolo!
				-- -------------------------------------------------------

				EXEC dbo.stp_QL_fullDataUpdate @QuoteType , @CodQuote , @QuoteRev, 'Y';

				--SELECT * FROM dbo.QuoteList WHERE QuoteType = 'C' AND CodQuote = @CodQuote
				--SELECT * FROM dbo.QuoteRM WHERE QuoteType = 'C' AND CodQuote = @CodQuote 
				--SELECT TOP(1000) * FROM dbo.QuoteFull_C WHERE QuoteType = 'C' AND CodQuote = @CodQuote 
			END

		SET @TotRow = @TotRow -1 -- decremento righe da leggere

--    COMMIT TRAN;
	END TRY
	BEGIN CATCH
		SELECT  'Error'
				,@CodItem
				,@CodClient          
				,@BatchQty           
				,@RawMat             
				,@RawMatCost         
				,@RawMatExtraCost    
				,@CodInco            
				, @TotRow
--        ROLLBACK

	 DECLARE @ErrorMessage NVARCHAR(4000);
	 DECLARE @ErrorSeverity INT;
	 DECLARE @ErrorState INT;

	SELECT    @ErrorMessage  = ERROR_MESSAGE() + ' Error Number: ' + CONVERT( Varchar(10) , ERROR_NUMBER())
											 + ' Severity: ' + CONVERT( Varchar(10) , ERROR_SEVERITY() ) + ' : '
											 + ISNULL(ERROR_PROCEDURE(),'stored?') 
											 + ' Line: ' + CONVERT(VARCHAR(100),ERROR_LINE()),

			@ErrorSeverity  = 8, -- ERROR_SEVERITY(),
			@ErrorState     = ERROR_STATE();

	RAISERROR (@ErrorMessage,  -- Message text.
			   @ErrorSeverity, -- Severity.
			   @ErrorState     -- State.
			   );


		SET @TotRow = @TotRow -1 -- decremento righe da leggere
	END CATCH

END                 -- END WHILE

/*
-- Pulizia Tabelle di appoggio x QuoteType = 'C'

DELETE FROM dbo.QuoteOC      WHERE QuoteType = 'C'
DELETE FROM dbo.QuoteParam   WHERE QuoteType = 'C'
DELETE FROM dbo.QuoteWorkExt WHERE QuoteType = 'C'
DELETE FROM dbo.QuoteWorkInt WHERE QuoteType = 'C'
DELETE FROM dbo.QuoteRM      WHERE QuoteType = 'C'
DELETE FROM dbo.QuoteList    WHERE QuoteType = 'C'

SELECT TOP 1000 * FROM dbo.QuoteList    WHERE QuoteType = 'C'  AND CodQuote = '14052600000001'
SELECT * FROM dbo.QuoteRM WHERE QuoteType = 'C'  AND CodQuote = '14052600000001'
SELECT TOP 1000 * FROM dbo.QuoteOC      WHERE QuoteType = 'C' AND CodQuote = '14052600000002'
SELECT TOP 1000 * FROM dbo.QuoteParam   WHERE QuoteType = 'C' AND CodQuote = '14052600000993'
SELECT TOP 1000 * FROM dbo.QuoteWorkInt WHERE QuoteType = 'C' AND CodQuote = '14052600000993'

SELECT TOP 1000 * FROM ItemDet WHERE CodItem = '1BQ00012' 

SELECT * FROM dbo.QuoteFull_C WHERE QuoteType = 'C' 

-- RIPULISCO TUTTO 
TRUNCATE TABLE dbo.QuoteFull_C

UPDATE dbo.ContatoriQuote
SET LastIdx = 0 WHERE Flusso = 'C'

*/

RETURN
GO
PRINT N'Creating [dbo].[stp_QLF_Insert]...';


GO

-- =============================================
-- Author:		Steamware - S.E.L.
-- Create date: 2014.04.16
-- Description:	insert di un record in QL (Full) e poi aggiorna a cascata
-- =============================================
CREATE PROCEDURE [dbo].[stp_QLF_Insert]
(
    @QuoteType			CHAR(1) = 'Q',
    @CodClient			NVARCHAR(50) = '',
    @CodItem			NVARCHAR(50) = '',
    @RawMat				NVARCHAR(50),
    @RawMatCost			DECIMAL(18, 6),
    @RawMatExtraCost	DECIMAL(18, 6),
    @BatchQty			INT,
    @CodInco			NVARCHAR(5),
    @Note				NVARCHAR(2500) = ''
)
AS

-- variabili
DECLARE	@CodQuote		BIGINT	= 0,
        @QuoteRev		INT		= 0

-- check QTA: deve essere > 0 !!!
IF(@BatchQty = 0)
BEGIN
    SET	@BatchQty = 1
END

SET XACT_ABORT ON;
BEGIN TRAN

    -- calcolo nuovo record odierno
    SELECT	@CodQuote = dbo.f_getNewCodQuote()

    -- inserisco riga in QuoteList
    INSERT INTO QuoteList(QuoteType, CodQuote, QuoteRev, CodClient, CodItem, UnitWeight, BatchQty, CodItemGroup, RawMat, CodInco, Note)
    SELECT      @QuoteType, @CodQuote, @QuoteRev, @CodClient, CodItem, UnitWeight, @BatchQty, CodItemGroup, @RawMat, @CodInco, @Note
    FROM        ItemDet
    WHERE       CodItem = @CodItem

    -- ora inserisco in QuoteRM
    INSERT INTO QuoteRM(QuoteType, CodQuote, QuoteRev, NumRM, RawMat, RawMatCost, RawMatExtraCost)
    VALUES      (@QuoteType, @CodQuote, @QuoteRev, 1, @RawMat, @RawMatCost, @RawMatExtraCost)
    
    -- ricalcolo!
    EXEC stp_QL_fullDataUpdate @QuoteType
            ,@CodQuote
            ,@QuoteRev
            ,'Y'

COMMIT TRAN

-- seleziono intera riga!    
SELECT	* 
FROM	v_QuoteFull_Q
WHERE	QuoteType	= @QuoteType
    AND CodQuote	= @CodQuote
    AND QuoteRev	= @QuoteRev


RETURN
GO
PRINT N'Creating [dbo].[stp_QLR_insNew]...';


GO
-- =============================================
-- Author:		Steamware
-- Mod. date:   2014.05.22
-- Description:	elaborazione OrdersHist Redditivity
-- =============================================
CREATE PROCEDURE [dbo].[stp_QLR_insNew]
(
    @QuoteType			CHAR(1)         = 'R',
    @Note				NVARCHAR(2500)  = '',
    @row2proc           INT             = 100
)
AS
BEGIN

SET NOCOUNT ON;

-- declare variabili
DECLARE	@CodQuote	        AS BIGINT,
        @QuoteRev	        AS INT	= 0,
        @OrdNum             AS NVARCHAR(50),
        @OrdRow             AS NVARCHAR(50),
        @CodItem            AS NVARCHAR(50),
        @CodClient          AS NVARCHAR(50),
        @BatchQty           AS INT,
        @RawMat             AS NVARCHAR(50),
        @RawMatCost         AS DECIMAL(18,6),
        @RawMatExtraCost    AS DECIMAL(18,6),
        @CodInco            AS NVARCHAR(5),
        @PriceOff           AS DECIMAL(9,6),
        @OrdDate            As DATETIME,
        @OrdPrice           AS DECIMAL(9,6),
        @OrdQty             AS INT,
        @ProvvCost          AS DECIMAL(9,6),
        @oggi               AS DATETIME = GETDATE(),
        @LastIdx            AS INT,
        @noRow              AS CHAR(1) = 'N'
            
SET XACT_ABORT ON;

SET @QuoteType = 'R'  -- per il momento non lascio parametrico il quotetype R - redditività

-- se non esiste il contatore creo il record
IF NOT EXISTS ( SELECT * FROM dbo.ContatoriQuote WHERE Flusso = @QuoteType )
    INSERT INTO  dbo.ContatoriQuote SELECT @QuoteType, 0

-- verifico se ci sono record da elaborare
IF EXISTS ( SELECT * FROM dbo.OrdersHist WHERE CodQuote = 0 ) 
   SET @noRow = 'N'

WHILE( @noRow = 'N' AND @row2proc > 0)
BEGIN
    -- ===========================================================
    -- stacco il CodQuote da usare e sbocco la tabella ( in realtà perdo un numero se poi non faccio insert )
    -- se non eseguo procedure multiple contemporanee non serve 
    -- ===========================================================
    -- SET TRANSACTION ISOLATION LEVEL SERIALIZABLE; -- credo non serva con OUTPUT
    DECLARE @Table TABLE ( LastIdx INT ) 
    BEGIN TRAN;
            UPDATE dbo.ContatoriQuote
                SET LastIdx = ( LastIdx % 1000000 ) + 1   -- si resetta dopo 1.000.000 righe ( in pratica ho tot righe x giorno )
            OUTPUT inserted.LastIdx INTO @Table
            WHERE Flusso = @QuoteType
        
            SELECT @LastIdx = MAX(LastIdx) FROM @Table
            SELECT @CodQuote = CONVERT( BIGINT, ( RIGHT(YEAR(@oggi),2) + dbo.f_padLeft(MONTH(@oggi), 2,'0') + dbo.f_padLeft(DAY(@oggi), 2,'0') + dbo.f_padLeft(@LastIdx, 8,'0') ) )
    COMMIT;

    -- ===========================================================
    -- elaboro il primo ordine "libero" assegnando il CodQuote
    -- se da errore la transazione mi annulla il codquote e quindi rimane elaborabile
    -- altrimenti metto l'assegnazione nella tran precedente e poi decido cosa fare con quelli non completati con data EndCalc = NULL
    -- ===========================================================
    -- SET TRANSACTION ISOLATION LEVEL REPEATABLE READ; -- SERIALIZABLE; -- REPEATABLE READ;
    BEGIN TRANSACTION;

        -- leggo il primo ordine da elaborare e assegno il CodQuote
        WITH cteOrderFree AS 
        (   -- leggo il primo ordine da elaborare e assegno il CodQuote
            SELECT TOP(1) OrdNum, OrdRow FROM dbo.OrdersHist WHERE CodQuote = 0
        )
        UPDATE Ord
            SET CodQuote     = @CodQuote,
                QuoteType    = @QuoteType
        FROM dbo.OrdersHist AS ord
        INNER JOIN cteOrderFree AS cte 
        ON ord.OrdNum = cte.OrdNum AND ord.OrdRow = cte.OrdRow


        -- leggo i valori di calcolo
        SET @OrdNum = NULL
        SELECT  @OrdNum             = OrdNum, 
                @OrdRow             = OrdRow , 
                @CodItem            = hi.CodItem,
                @CodClient          = CodClient,
                @BatchQty           = BatchQty,
                @RawMat             = RawMat,
                @RawMatCost         = RawMatCost,
                @RawMatExtraCost    = RawMatExtraCost,
                @CodInco            = CodInco,
                @PriceOff           = PriceOff,
                @OrdPrice           = OrdPrice,
                @OrdDate            = OrdDate,
                @OrdQty             = OrdQty,
                @ProvvCost          = ProvvCost
        FROM dbo.OrdersHist hi
        INNER JOIN dbo.ItemDet AS It ON hi.CodItem = it.CodItem     -- deve esistere il codice in anagrafica altrimenti non lo elaboro
        WHERE CodQuote = @CodQuote AND QuoteType = @QuoteType
        OPTION (RECOMPILE)

        IF @OrdNum IS NOT NULL    -- record precedente trovato 
            BEGIN

                -- inserisco riga in QuoteList
                INSERT INTO dbo.QuoteList( QuoteType, CodQuote, QuoteRev, CodClient, CodItem, UnitWeight, BatchQty, CodItemGroup, RawMat, CodInco, Note, PriceOff, OrdNum, OrdRow, OrdDate, OrdPrice, OrdQty )
                SELECT      @QuoteType, @CodQuote, @QuoteRev, @CodClient, CodItem, UnitWeight, @BatchQty, CodItemGroup, @RawMat, @CodInco, @Note , @PriceOff, @OrdNum, @OrdRow, @OrdDate ,@OrdPrice, @OrdQty
                FROM        dbo.ItemDet
                WHERE       CodItem = @CodItem

                -- ora inserisco in QuoteRM
                INSERT INTO dbo.QuoteRM(QuoteType, CodQuote, QuoteRev, NumRM, RawMat, RawMatCost, RawMatExtraCost)
                VALUES      (@QuoteType, @CodQuote, @QuoteRev, 1, @RawMat, @RawMatCost, @RawMatExtraCost)
    
                -- ora inserisco ProvvCost in QuoteSimPar che mi serve dopo nei calcoli dopo
                INSERT INTO dbo.QuoteSimPar(QuoteType, CodQuote, QuoteRev, NomePar, ValPar)
                VALUES      (@QuoteType, @CodQuote, @QuoteRev, 'ProvvCost', @ProvvCost)

                -- ricalcolo!
                EXEC dbo.stp_QL_fullDataUpdate @QuoteType , @CodQuote , @QuoteRev, 'Y';

                -- aggiorno data-ora fine elaborazione
                UPDATE dbo.OrdersHist
                    SET EndCalc = GETDATE()
                WHERE CodQuote = @CodQuote AND QuoteType = @QuoteType;

                --SELECT * FROM dbo.OrdersHist WHERE QuoteType = 'R' AND CodQuote = @CodQuote
                --SELECT * FROM dbo.QuoteList WHERE QuoteType = 'R' AND CodQuote = @CodQuote
                --SELECT * FROM dbo.QuoteRM WHERE QuoteType = 'R' AND CodQuote = @CodQuote 
                --SELECT TOP(1000) * FROM dbo.QuoteFull_R WHERE QuoteType = 'R' AND CodQuote = @CodQuote 
            END
        ELSE
            SET @noRow = 'Y'   -- fine righe da elaborare

    COMMIT TRAN;
    SET @row2proc = @row2proc - 1

END    -- END WHILE

RETURN

END

/*
-- Pulizia Tabelle di appoggio x QuoteType = 'R'

DELETE FROM dbo.QuoteOC      WHERE QuoteType = 'R'
DELETE FROM dbo.QuoteParam   WHERE QuoteType = 'R'
DELETE FROM dbo.QuoteWorkExt WHERE QuoteType = 'R'
DELETE FROM dbo.QuoteWorkInt WHERE QuoteType = 'R'
DELETE FROM dbo.QuoteRM      WHERE QuoteType = 'R'
DELETE FROM dbo.QuoteList    WHERE QuoteType = 'R'
DELETE FROM dbo.QuoteSimPar  WHERE QuoteType = 'R'

SELECT TOP 1000 * FROM dbo.QuoteList    WHERE QuoteType = 'R'
SELECT TOP 1000 * FROM dbo.QuoteRM      WHERE QuoteType = 'R'
SELECT TOP 1000 * FROM dbo.QuoteOC      WHERE QuoteType = 'R'
SELECT TOP 1000 * FROM dbo.QuoteParam   WHERE QuoteType = 'R'
SELECT TOP 1000 * FROM dbo.QuoteWorkExt WHERE QuoteType = 'R'
SELECT TOP 1000 * FROM dbo.QuoteWorkInt WHERE QuoteType = 'R'

SELECT * FROM dbo.OrdersHist
SELECT * FROM dbo.QuoteFull_R WHERE QuoteType = 'R' 

-- RIPULISCO TUTTO 
TRUNCATE TABLE dbo.QuoteFull_R

UPDATE dbo.OrdersHist 
SET CodQuote = 0

UPDATE dbo.ContatoriQuote
SET LastIdx = 0 WHERE Flusso = 'R'

-- SE RICARICO DA ZERO GLI ORDINI 
TRUNCATE TABLE dbo.OrdersHist

*/
GO
PRINT N'Creating [dbo].[stp_QLS_UpdHead]...';


GO

-- =============================================
-- Author:		Steamware - S.E.L.
-- Create date: 2014.05.16
-- Description:	update di un record in QL (Full) TIPO SIMULAZIONE e poi aggiorna a cascata
-- =============================================
CREATE PROCEDURE [dbo].[stp_QLS_UpdHead]
(
    @Original_QuoteType CHAR(1) = 'S',
    @Original_CodQuote	BIGINT = 0,
    @Original_QuoteRev	INT = 0,
    @CodClient			NVARCHAR(50) = '',
    @CodItem			NVARCHAR(50) = '',
    @UnitWeight			DECIMAL(9, 3) = 0,
    @CodItemGroup		NVARCHAR(50) = '',
    @RawMat				NVARCHAR(50),
    @RawMatCost			DECIMAL(18, 6),
    @RawMatExtraCost	DECIMAL(18, 6),
    @BatchQty			INT,
    @CodInco			NVARCHAR(5),
	@ProvvCost			DECIMAL(18,6),
    @Note				NVARCHAR(2500) = ''
)
AS

SET XACT_ABORT ON;
BEGIN TRAN
    -- aggiorno valori QuoteList!
    UPDATE	QuoteList
    SET		CodClient	= @CodClient
        ,	CodItem		= @CodItem
        ,	RawMat		= @RawMat
        ,	BatchQty	= @BatchQty
        ,	CodInco		= @CodInco
        ,	Note		= ISNULL(@Note,'')
        ,	CodItemGroup= @CodItemGroup
        ,	UnitWeight	= @UnitWeight
    WHERE	QuoteType = @Original_QuoteType
        AND CodQuote = @Original_CodQuote
        AND QuoteRev = @Original_QuoteRev
        
    -- aggiorno valori QuoteRM
    UPDATE QuoteRM
    SET		RawMat		= @RawMat
        ,	RawMatCost	= @RawMatCost
        ,	RawMatExtraCost	= @RawMatExtraCost
    WHERE	QuoteType = @Original_QuoteType
        AND CodQuote = @Original_CodQuote
        AND QuoteRev = @Original_QuoteRev

        
    -- @CodDiesGroup
    DECLARE	@CodDiesGroup	NVARCHAR(50) = ''
    SELECT	@CodDiesGroup	= ValPar
    FROM	QuoteSimPar
    WHERE	QuoteType	= @Original_QuoteType 
        AND	CodQuote	= @Original_CodQuote	
        AND	QuoteRev	= @Original_QuoteRev
        AND	NomePar		= 'CodDiesGroup'

    -- scambio ultimo valore
    SELECT	@CodDiesGroup = ISNULL(REPLACE(@CodDiesGroup, '-' + dbo.f_GetSubstring(@CodDiesGroup,'-' , 4), '-'+@CodItemGroup), '' )
	
    EXEC stp_QSP_upsert @Original_QuoteType, @Original_CodQuote, @Original_QuoteRev, 'CodDiesGroup', @CodDiesGroup
    EXEC stp_QSP_upsert @Original_QuoteType, @Original_CodQuote, @Original_QuoteRev, 'ProvvCost', @ProvvCost


    -- update dei valori calcolati!
    EXEC stp_QL_fullDataUpdate @Original_QuoteType
        ,@Original_CodQuote
        ,@Original_QuoteRev
        ,'Y'
        
COMMIT TRAN


-- seleziono intera riga!
    
SELECT	* 
FROM	v_QuoteFull_Q
WHERE	QuoteType = @Original_QuoteType
    AND CodQuote = @Original_CodQuote
    AND QuoteRev = @Original_QuoteRev


RETURN
GO
PRINT N'Creating [dbo].[stp_QLS_UpdExtrPar]...';


GO
-- =============================================
-- Author:		Steamware - S.E.L.
-- Create date: 2014.05.16
-- Description:	update di un record in QL (Full) TIPO SIMULAZIONE e poi aggiorna a cascata
-- =============================================
CREATE PROCEDURE [dbo].[stp_QLS_UpdExtrPar]
(
	@Original_QuoteType CHAR(1) = 'S',
	@Original_CodQuote	BIGINT = 0,
	@Original_QuoteRev	INT = 0,
	@TipoDies			NVARCHAR(50) = '',	
	@DiamDies			INT = 1,	
	@HoleNumDies		INT = 1,	
	@CodPlant	        NVARCHAR(50),
	@DiesPrice_sim      DECIMAL(18, 6),
	@DiesTecLife        DECIMAL(18, 6),
	@WSR01_sim          DECIMAL(9, 8),
	@MSR01_sim          DECIMAL(9, 8),
	@NetProd01_sim      DECIMAL(9, 3)
)
AS

SET XACT_ABORT ON;
BEGIN TRAN

	-- dichiaro e calcolo valore complessivo...
	DECLARE	@CodDiesGroup	NVARCHAR(50) = ''

	SELECT	@CodDiesGroup	=  @TipoDies + '-' + CAST(@DiamDies AS VARCHAR(50)) + '-' + CAST(@HoleNumDies AS VARCHAR(50)) + '-' + CodItemGroup
	FROM	QuoteList
	WHERE	QuoteType	= @Original_QuoteType 
		AND	CodQuote	= @Original_CodQuote	
		AND	QuoteRev	= @Original_QuoteRev	


	-- @CodDiesGroup
	EXEC stp_QSP_upsert @Original_QuoteType, @Original_CodQuote, @Original_QuoteRev, 'CodDiesGroup', @CodDiesGroup
	
	-- @CodPlant
	EXEC stp_QSP_upsert @Original_QuoteType, @Original_CodQuote, @Original_QuoteRev, 'CodPlant', @CodPlant
	
	-- @DiesPrice_sim
	EXEC stp_QSP_upsert @Original_QuoteType, @Original_CodQuote, @Original_QuoteRev, 'DiesPrice_sim', @DiesPrice_sim
	
	-- @DiesTecLife
	EXEC stp_QSP_upsert @Original_QuoteType, @Original_CodQuote, @Original_QuoteRev, 'DiesTecLife', @DiesTecLife
	
	-- @WSR01_sim
	EXEC stp_QSP_upsert @Original_QuoteType, @Original_CodQuote, @Original_QuoteRev, 'WSR01_sim', @WSR01_sim
	
	-- @MSR01_sim
	EXEC stp_QSP_upsert @Original_QuoteType, @Original_CodQuote, @Original_QuoteRev, 'MSR01_sim', @MSR01_sim
	
	-- @NetProd01_sim
	EXEC stp_QSP_upsert @Original_QuoteType, @Original_CodQuote, @Original_QuoteRev, 'NetProd01_sim', @NetProd01_sim
	

	-- update dei valori calcolati!
	EXEC stp_QL_fullDataUpdate @Original_QuoteType
		,@Original_CodQuote
		,@Original_QuoteRev
		,'Y'

	-- 2014.10.12 modifica sam: chiamo 2 volte perché è simulazione e i valori _sim sono salvati alla fine ed usati all'inizio...
    EXEC stp_QL_fullDataUpdate @Original_QuoteType
        ,@Original_CodQuote
        ,@Original_QuoteRev
        ,'Y'
			
COMMIT TRAN


-- seleziono intera riga!
	
SELECT	* 
FROM	v_QuoteFull_Q
WHERE	QuoteType = @Original_QuoteType
	AND CodQuote = @Original_CodQuote
	AND QuoteRev = @Original_QuoteRev


RETURN
GO
PRINT N'Creating [dbo].[stp_QL_newRev]...';


GO
-- =============================================
-- Author:		Steamware
-- Create date: 2014.04.23
-- Description:	duplica record QuoteList generando una NUOVA REVISIONE
-- =============================================
CREATE PROCEDURE [dbo].[stp_QL_newRev]
(
	@QuoteType		CHAR(1) = 'Q',
	@CodQuote		BIGINT	= 0,
	@QuoteRev_orig	INT		= 0
)
AS

-- variabili
DECLARE	@QuoteRev	INT = 0

SET		@QuoteRev = @QuoteRev_orig + 1

SET XACT_ABORT ON;
BEGIN TRAN

	-- inserisco riga in QuoteList
	INSERT INTO QuoteList(QuoteType, CodQuote, QuoteRev, CodClient, CodItem, UnitWeight, BatchQty, CodItemGroup, RawMat, CodInco, Note)
	SELECT      QuoteType, @CodQuote, @QuoteRev as QuoteRev, CodClient, CodItem, UnitWeight, BatchQty, CodItemGroup, RawMat, CodInco, Note
	FROM        QuoteList
	WHERE		QuoteType = @QuoteType
			AND	CodQuote = @CodQuote
			AND	QuoteRev = @QuoteRev_orig

	-- ora inserisco in QuoteRM
	INSERT INTO QuoteRM(QuoteType, CodQuote, QuoteRev, NumRM, RawMat, RawMatCost, RawMatExtraCost)
	SELECT      QuoteType, @CodQuote, @QuoteRev as QuoteRev, NumRM, RawMat, RawMatCost, RawMatExtraCost
	FROM        QuoteRM
	WHERE		QuoteType = @QuoteType
			AND	CodQuote = @CodQuote
			AND	QuoteRev = @QuoteRev_orig
	
	-- se la scheda di destinazione è simulazione
	IF(@QuoteType = 'S')
		BEGIN 
			EXEC stp_QL_copyParamS @QuoteType, @QuoteType, @CodQuote, @CodQuote, @QuoteRev, @QuoteRev_orig	
		END

	-- ricalcolo!
	EXEC stp_QL_fullDataUpdate @QuoteType
			,@CodQuote
			,@QuoteRev
			,'Y'

	    -- PATCH 2014/10 rieseguo ricalcolo x problema parametri simulati mancanti in quoteparam
    EXEC stp_QL_fullDataUpdate @QuoteType
            , @CodQuote
            , @QuoteRev
            , 'Y'

COMMIT TRAN

-- seleziono intera riga!
SELECT	* 
FROM	QuoteList
WHERE	QuoteType = @QuoteType
	AND	CodQuote = @CodQuote
	AND	QuoteRev = @QuoteRev

RETURN
GO
PRINT N'Creating [dbo].[stp_QL_makeSim]...';


GO
-- =============================================
-- Author:		Steamware
-- Mod date: 2014.10.01
-- Description:	modifica una quotazione da Q ad S in QuoteList e ricalcola
-- =============================================
CREATE PROCEDURE [dbo].[stp_QL_makeSim]
(
    @CodQuote_orig	BIGINT	= 0,
    @QuoteRev_orig	INT		= 0
)
AS

SET XACT_ABORT ON;
BEGIN TRAN

    -- passo x definizione a 'S'
    DECLARE	@QuoteType_orig	CHAR(1) = 'Q',
            @QuoteType		CHAR(1) = 'S'
    
    -- elimino record in QuoteFull_Q
    DELETE 
    FROM	QuoteFull_Q
    WHERE		QuoteType = @QuoteType_orig
            AND	CodQuote = @CodQuote_orig
            AND	QuoteRev = @QuoteRev_orig

    -- carico alcuni dati accessori precompilando...
    INSERT INTO QuoteSimPar(QuoteType, CodQuote, QuoteRev, NomePar, ValPar)
    SELECT  @QuoteType, @CodQuote_orig, @QuoteRev_orig, Descr, Parameter
    FROM    QuoteParam
    WHERE		QuoteType = @QuoteType_orig
            AND	CodQuote = @CodQuote_orig
            AND	QuoteRev = @QuoteRev_orig
            AND Descr IN ('CodDiesGroup', 'CodPlant')
    
    INSERT INTO QuoteSimPar(QuoteType, CodQuote, QuoteRev, NomePar, ValPar)
    SELECT  @QuoteType, @CodQuote_orig, @QuoteRev_orig, 'DiesTecLife', Parameter
    FROM    QuoteParam
    WHERE		QuoteType = @QuoteType_orig
            AND	CodQuote = @CodQuote_orig
            AND	QuoteRev = @QuoteRev_orig
            AND Descr = 'KgTeo'
                    
    INSERT INTO QuoteSimPar(QuoteType, CodQuote, QuoteRev, NomePar, ValPar)
    SELECT  @QuoteType, @CodQuote_orig, @QuoteRev_orig, 'DiesPrice_sim', Parameter
    FROM    QuoteParam
    WHERE		QuoteType = @QuoteType_orig
            AND	CodQuote = @CodQuote_orig
            AND	QuoteRev = @QuoteRev_orig
            AND Descr = 'DiesPrice'

    INSERT INTO QuoteSimPar(QuoteType, CodQuote, QuoteRev, NomePar, ValPar)
    SELECT  @QuoteType, @CodQuote_orig, @QuoteRev_orig, 'CodPackag', CodPackag
    FROM    QuoteRM
    WHERE		QuoteType = @QuoteType_orig
            AND	CodQuote = @CodQuote_orig
            AND	QuoteRev = @QuoteRev_orig
            
    INSERT INTO QuoteSimPar(QuoteType, CodQuote, QuoteRev, NomePar, ValPar)
    SELECT  @QuoteType, @CodQuote_orig, @QuoteRev_orig, 'NetProd01_sim', NetProd
    FROM    QuoteWorkInt
    WHERE		QuoteType = @QuoteType_orig
            AND	CodQuote = @CodQuote_orig
            AND	QuoteRev = @QuoteRev_orig
            AND	ProcessNum = '01'
            
    INSERT INTO QuoteSimPar(QuoteType, CodQuote, QuoteRev, NomePar, ValPar)
    SELECT  @QuoteType, @CodQuote_orig, @QuoteRev_orig, 'NetProd04_sim', NetProd
    FROM    QuoteWorkInt
    WHERE		QuoteType = @QuoteType_orig
            AND	CodQuote = @CodQuote_orig
            AND	QuoteRev = @QuoteRev_orig
            AND	ProcessNum = '04'
            
    INSERT INTO QuoteSimPar(QuoteType, CodQuote, QuoteRev, NomePar, ValPar)
    SELECT  @QuoteType, @CodQuote_orig, @QuoteRev_orig, 'MSR01_sim', MSR
    FROM    QuoteWorkInt
    WHERE		QuoteType = @QuoteType_orig
            AND	CodQuote = @CodQuote_orig
            AND	QuoteRev = @QuoteRev_orig
            AND	ProcessNum = '01'

    INSERT INTO QuoteSimPar(QuoteType, CodQuote, QuoteRev, NomePar, ValPar)
    SELECT  @QuoteType, @CodQuote_orig, @QuoteRev_orig, 'WSR01_sim', WSR
    FROM    QuoteWorkInt
    WHERE		QuoteType = @QuoteType_orig
            AND	CodQuote = @CodQuote_orig
            AND	QuoteRev = @QuoteRev_orig
            AND	ProcessNum = '01'            
            
    INSERT INTO QuoteSimPar(QuoteType, CodQuote, QuoteRev, NomePar, ValPar)
    SELECT  @QuoteType, @CodQuote_orig, @QuoteRev_orig, 'DSR_sim', DSR
    FROM    QuoteWorkInt
    WHERE		QuoteType = @QuoteType_orig
            AND	CodQuote = @CodQuote_orig
            AND	QuoteRev = @QuoteRev_orig
            AND	ProcessNum = '04'

    -- update riga in QuoteList
    UPDATE	QuoteList
    SET		QuoteType = @QuoteType
    WHERE		QuoteType = @QuoteType_orig
            AND	CodQuote = @CodQuote_orig
            AND	QuoteRev = @QuoteRev_orig

    -- ricalcolo!
    EXEC stp_QL_fullDataUpdate @QuoteType
            , @CodQuote_orig
            , @QuoteRev_orig
            , 'Y'

    -- PATCH 2014/10 rieseguo ricalcolo x problema parametri simulati mancanti in quoteparam
    EXEC stp_QL_fullDataUpdate @QuoteType
            , @CodQuote_orig
            , @QuoteRev_orig
            , 'Y'

COMMIT TRAN

-- seleziono intera riga!
SELECT	* 
FROM	QuoteList
WHERE	QuoteType = @QuoteType
    AND	CodQuote = @CodQuote_orig
    AND	QuoteRev = @QuoteRev_orig

RETURN
GO
PRINT N'Creating [dbo].[stp_QL_clone]...';


GO
-- =============================================
-- Author:		Steamware
-- Create date: 2014.04.23
-- Description:	duplica record QuoteList
-- =============================================
CREATE PROCEDURE [dbo].[stp_QL_clone]
(
	@QuoteType		CHAR(1) = 'Q',
	@QuoteType_orig	CHAR(1) = 'Q',
	@CodQuote_orig	BIGINT	= 0,
	@QuoteRev_orig	INT		= 0
)
AS

-- variabili
DECLARE	@CodQuote	BIGINT	= 0,
		@QuoteRev	INT = 0

SET XACT_ABORT ON;
BEGIN TRAN

	-- calcolo nuovo record odierno
	SELECT	@CodQuote = dbo.f_getNewCodQuote()

	-- inserisco riga in QuoteList
	INSERT INTO QuoteList(QuoteType, CodQuote, QuoteRev, CodClient, CodItem, UnitWeight, BatchQty, CodItemGroup, RawMat, CodInco, Note, PriceOff)
	SELECT      @QuoteType, @CodQuote, @QuoteRev as QuoteRev, CodClient, CodItem, UnitWeight, BatchQty, CodItemGroup, RawMat, CodInco, 'CLONE - ' + Note, PriceOff
	FROM        QuoteList
	WHERE		QuoteType = @QuoteType_orig
			AND	CodQuote = @CodQuote_orig
			AND	QuoteRev = @QuoteRev_orig

	-- ora inserisco in QuoteRM
	INSERT INTO QuoteRM(QuoteType, CodQuote, QuoteRev, NumRM, RawMat, RawMatCost, RawMatExtraCost)
	SELECT      @QuoteType, @CodQuote, @QuoteRev as QuoteRev, NumRM, RawMat, RawMatCost, RawMatExtraCost
	FROM        QuoteRM
	WHERE		QuoteType = @QuoteType_orig
			AND	CodQuote = @CodQuote_orig
			AND	QuoteRev = @QuoteRev_orig



	-- se la scheda di destinazione è simulazione
	IF(@QuoteType = 'S')
		BEGIN 
			EXEC stp_QL_copyParamS @QuoteType, @QuoteType_orig, @CodQuote, @CodQuote_orig, @QuoteRev, @QuoteRev_orig	

			/*
			IF(@QuoteType_orig = 'S')			
			-- se partenza è S duplico dati accessori...
				BEGIN
					INSERT INTO QuoteSimPar(QuoteType, CodQuote, QuoteRev, NomePar, ValPar)
					SELECT  @QuoteType, @CodQuote, @QuoteRev, NomePar, ValPar
					FROM    QuoteSimPar
					WHERE		QuoteType = @QuoteType_orig
							AND	CodQuote = @CodQuote_orig
							AND	QuoteRev = @QuoteRev_orig
				END
			ELSE
			-- se partenza è Q carico alcuni dati accessori precompilando...
				BEGIN				
					INSERT INTO QuoteSimPar(QuoteType, CodQuote, QuoteRev, NomePar, ValPar)
					SELECT  @QuoteType, @CodQuote, @QuoteRev, Descr, Parameter
					FROM    QuoteParam
					WHERE		QuoteType = @QuoteType_orig
							AND	CodQuote = @CodQuote_orig
							AND	QuoteRev = @QuoteRev_orig
							AND Descr IN ('CodDiesGroup', 'CodPlant')
					
					INSERT INTO QuoteSimPar(QuoteType, CodQuote, QuoteRev, NomePar, ValPar)
					SELECT  @QuoteType, @CodQuote, @QuoteRev, 'DiesTecLife', Parameter
					FROM    QuoteParam
					WHERE		QuoteType = @QuoteType_orig
							AND	CodQuote = @CodQuote_orig
							AND	QuoteRev = @QuoteRev_orig
							AND Descr = 'KgTeo'
					
					INSERT INTO QuoteSimPar(QuoteType, CodQuote, QuoteRev, NomePar, ValPar)
					SELECT  @QuoteType, @CodQuote, @QuoteRev, 'DiesPrice_sim', Parameter
					FROM    QuoteParam
					WHERE		QuoteType = @QuoteType_orig
							AND	CodQuote = @CodQuote_orig
							AND	QuoteRev = @QuoteRev_orig
							AND Descr = 'DiesPrice'
					
					INSERT INTO QuoteSimPar(QuoteType, CodQuote, QuoteRev, NomePar, ValPar)
					SELECT  @QuoteType, @CodQuote, @QuoteRev, 'CodPackag', CodPackag
					FROM    QuoteRM
					WHERE		QuoteType = @QuoteType_orig
							AND	CodQuote = @CodQuote_orig
							AND	QuoteRev = @QuoteRev_orig
					
					INSERT INTO QuoteSimPar(QuoteType, CodQuote, QuoteRev, NomePar, ValPar)
					SELECT  @QuoteType, @CodQuote, @QuoteRev, 'NetProd01_sim', NetProd
					FROM    QuoteWorkInt
					WHERE		QuoteType = @QuoteType_orig
							AND	CodQuote = @CodQuote_orig
							AND	QuoteRev = @QuoteRev_orig
							AND	ProcessNum = '01'
							
					INSERT INTO QuoteSimPar(QuoteType, CodQuote, QuoteRev, NomePar, ValPar)
					SELECT  @QuoteType, @CodQuote, @QuoteRev, 'NetProd04_sim', NetProd
					FROM    QuoteWorkInt
					WHERE		QuoteType = @QuoteType_orig
							AND	CodQuote = @CodQuote_orig
							AND	QuoteRev = @QuoteRev_orig
							AND	ProcessNum = '04'
					
					INSERT INTO QuoteSimPar(QuoteType, CodQuote, QuoteRev, NomePar, ValPar)
					SELECT  @QuoteType, @CodQuote, @QuoteRev, 'MSR01_sim', MSR
					FROM    QuoteWorkInt
					WHERE		QuoteType = @QuoteType_orig
							AND	CodQuote = @CodQuote_orig
							AND	QuoteRev = @QuoteRev_orig
							AND	ProcessNum = '01'
					
					INSERT INTO QuoteSimPar(QuoteType, CodQuote, QuoteRev, NomePar, ValPar)
					SELECT  @QuoteType, @CodQuote, @QuoteRev, 'WSR01_sim', WSR
					FROM    QuoteWorkInt
					WHERE		QuoteType = @QuoteType_orig
							AND	CodQuote = @CodQuote_orig
							AND	QuoteRev = @QuoteRev_orig
							AND	ProcessNum = '01'
					
					INSERT INTO QuoteSimPar(QuoteType, CodQuote, QuoteRev, NomePar, ValPar)
					SELECT  @QuoteType, @CodQuote, @QuoteRev, 'DSR_sim', DSR
					FROM    QuoteWorkInt
					WHERE		QuoteType = @QuoteType_orig
							AND	CodQuote = @CodQuote_orig
							AND	QuoteRev = @QuoteRev_orig
							AND	ProcessNum = '04'
				END
				*/	
		END

	-- ricalcolo!
	EXEC stp_QL_fullDataUpdate @QuoteType
			,@CodQuote
			,@QuoteRev
			,'Y'

	    -- PATCH 2014/10 rieseguo ricalcolo x problema parametri simulati mancanti in quoteparam
    EXEC stp_QL_fullDataUpdate @QuoteType
            , @CodQuote
            , @QuoteRev
            , 'Y'

COMMIT TRAN

-- seleziono intera riga!
SELECT	* 
FROM	QuoteList
WHERE	QuoteType = @QuoteType
	AND	CodQuote = @CodQuote
	AND	QuoteRev = @QuoteRev

RETURN
GO
PRINT N'Creating [dbo].[stp_QLS_UpdPackPar]...';


GO
-- =============================================
-- Author:		Steamware - S.E.L.
-- Create date: 2014.05.20
-- Description:	update di un record in QL (Full) TIPO SIMULAZIONE e poi aggiorna a cascata
-- =============================================
CREATE PROCEDURE [dbo].[stp_QLS_UpdPackPar]
(
    @Original_QuoteType CHAR(1) = 'S',
    @Original_CodQuote	BIGINT = 0,
    @Original_QuoteRev	INT = 0,
    @CodPackag	        NVARCHAR(50),
    @DSR_sim            DECIMAL(9, 8),
	@NetProd04_sim      DECIMAL(9, 3)
)
AS

SET XACT_ABORT ON;
BEGIN TRAN

    -- @CodPackag
    EXEC stp_QSP_upsert @Original_QuoteType, @Original_CodQuote, @Original_QuoteRev, 'CodPackag', @CodPackag
    
    -- @DSR_sim
    EXEC stp_QSP_upsert @Original_QuoteType, @Original_CodQuote, @Original_QuoteRev, 'DSR_sim', @DSR_sim
    
	-- @NetProd04_sim
	EXEC stp_QSP_upsert @Original_QuoteType, @Original_CodQuote, @Original_QuoteRev, 'NetProd04_sim', @NetProd04_sim

    -- update dei valori calcolati!
    EXEC stp_QL_fullDataUpdate @Original_QuoteType
        ,@Original_CodQuote
        ,@Original_QuoteRev
        ,'Y'
        
	-- la chiamo 2 volte perché è simulazione e i valori _sim sono salvati alla fine ed usati all'inizio...
    EXEC stp_QL_fullDataUpdate @Original_QuoteType
        ,@Original_CodQuote
        ,@Original_QuoteRev
        ,'Y'
        

COMMIT TRAN


-- seleziono intera riga!
    
SELECT	* 
FROM	v_QuoteFull_Q
WHERE	QuoteType = @Original_QuoteType
    AND CodQuote = @Original_CodQuote
    AND QuoteRev = @Original_QuoteRev


RETURN
GO
PRINT N'Creating [dbo].[stp_zzz_scratchDatiDemo]...';


GO



-- =============================================
-- Author:		G.A.R.
-- Create date: 2014.05.12
-- Description:	Procedura sostituzione dati con dati DEMO
-- =============================================
CREATE PROCEDURE [dbo].[stp_zzz_scratchDatiDemo] 
AS
BEGIN
	
    -- dichiaro e imposto periodo di calcolo dei valori
    -- andrà impostato in una tabella e mi determinerà la versione dei dati
    DECLARE @dateFrom AS DateTime;
    DECLARE @dateTo   AS DateTime;

    SET @dateFrom = '20100101' 
    SET @dateTo   = '20130929'

    -- ==========================================
    -- IMPORTAZIONE DATI CSV --- QUI NON SERVER DATI GIA' CARICATI
    -- ==========================================
 --   exec tmp.importProductionLogRaw
	--exec tmp.importClientsRaw
	--exec tmp.importTranspCostRaw
	--exec tmp.importItemsRaw
	--exec tmp.importPackagRaw
	--exec tmp.importDiesRaw
    --   -- questo sotto va fatto solo se ci sono dati da integrare in DiesRaw
	--exec tmp.importDiesGroupRaw
	--select top 10 *  FROM tmp.ProductionLogRaw
	--select *  FROM tmp.ClientsRaw
	--select *  FROM tmp.ItemsRaw
	--select *  FROM tmp.PackagRaw
	--select *  FROM tmp.DiesRaw
	--select *  FROM tmp.DiesGroupRaw

    -- Se ci sono record con Item doppi li cancello????
	--SELECT CodItem,COUNT(*) as qty
	--FROM ( SELECT DISTINCT * FROM tmp.ItemsRaw ) AS a
	--GROUP BY  CodItem
	--having COUNT(*)>1

	--delete from tmp.ItemsRaw
	--where CodItem IN
	--(
	--    SELECT CodItem
	--    FROM ( SELECT DISTINCT * FROM tmp.ItemsRaw ) AS a
	--    GROUP BY CodItem
	--    having COUNT(*)>1
	--)
	

    -- ===========================================================
    -- CARICO DATI IN RAW EXT ( da Char a Tipi corretti ) cancella e carica da Tabelle TMP
    -- ===========================================================
	exec tmp.convertClientsRaw
	exec tmp.convertTranspCostRaw
	exec tmp.convertItemsRaw
	exec tmp.convertProductionLogRaw
	exec tmp.convertPackagRaw
	exec tmp.convertDiesRaw

	-- necessario se integriamo i dati x i gruppi di matrici con un file
	exec tmp.convertDiesGroupRaw
--	exec tmp.convertDiesGroupRaw 'DiesDet'   -- integro i gruppi mancanti ??? TOLTO

	select top 10 * FROM ext.ProductionLogRaw
	select *  FROM ext.ClientsRaw
	select *  FROM ext.ItemsRaw
	select *  FROM ext.PackagRaw
	select *  FROM ext.DiesRaw
    SELECT *  FROM ext.DiesGroupRaw

	-- elimino a mano dato con oltre 68 anni di evento... prob. non serve più
	--select * 
	----delete
	--from ext.ProductionLogRaw where DATEDIFF(YEAR,EventStart,EventEnd)> 10

    -- =======================================
    -- cancello le tabelle che ricarico
    -- =======================================

    -- exec ext.stp_mergeAgentsDet          -- NON DEMO  campi non modificati x DEMO

    TRUNCATE TABLE dbo.ProductionLog
    TRUNCATE TABLE dbo.Package2ItemClient
    TRUNCATE TABLE dbo.Package2Item
    TRUNCATE TABLE dbo.Cost2Plant     -- forse meglio non cancellarli e sostituirli in import? ma se non li ho in anagrafica non riesco!!!
    DELETE FROM dbo.PlantsDet
    DELETE FROM dbo.ClientDet

	exec ext.stp_mergeClientDet     'ProductionLogRaw'
	exec ext.stp_mergeClientDet     'ClientsRaw'

	-- exec ext.stp_mergeTranspCostDet 'TranspCostRaw'  -- NON DEMO
	exec ext.stp_mergePlantsDet                      
	-- exec ext.stp_mergeCost2Plant   non carica i valori caricati a mano dopo
    
    TRUNCATE TABLE dbo.DiesDet
    DELETE FROM dbo.DiesGroupDet
    DELETE FROM  dbo.ItemDet
	exec ext.stp_mergeItemDet               'ItemsRaw'
    exec ext.stp_mergePackagDet             'ProductionLogRaw'                      -- 'PackagRaw'

	exec ext.stp_mergeDiesDet
	-- se ricarico diesgroup... ricarico solo i campi che nel file sono <> ''
	exec ext.stp_mergeDiesGroupDet

    DELETE FROM dbo.RawMatDet
	exec ext.stp_mergeRawMat
	exec ext.stp_updateProductionLog

    --DECLARE @dateFrom AS DateTime;
    --DECLARE @dateTo   AS DateTime;

    --SET @dateFrom = '20100101' 
    --SET @dateTo   = '20130929'
	exec ext.stp_mergePackage2ItemClient    'ProductionLog', @dateFrom, @dateTo
	exec ext.stp_mergePackage2Item          'ProductionLog', @dateFrom, @dateTo
	exec ext.stp_mergePackage2              'ProductionLog', @dateFrom, @dateTo

    -- =========================================================================
    -- aggiorno CodPlan nelle Utilities   ( sono state caricate a mano ??? )
    -- =========================================================================
    SELECT * FROM utilities
    UPDATE Utilities
        SET CodPlant = tp.CodPlantNew
    FROM Utilities AS u
    INNER JOIN TrascPlan tp ON u.CodPlant = tp.CodPlant

	---- aggiorno quota agenti a 0.037
	----update AgentsDet set quotaperc=0.0374

	--SELECT DISTINCT dr.CodItem FROM ext.DiesRaw dr LEFT OUTER JOIN ItemDet id ON dr.CodItem = id.CodItem
	--where id.CodItemGroup is null

	select * from ClientDet
	select * from ItemDet
	select * from Package2ItemClient
	select * from Package2Item
	select * from Package2
	select * from PackagDet
	select * from DiesGroupDet where EOLLife > 0
	select * from DiesDet
	select * from DiesGroupDet
	select * from AgentsDet
	select * from PlantsDet
	select * from Cost2Plant
	select * from utilities
	select top 100 * from ProductionLog

	--update tmp.ProductionLogRaw
	--set
	--	okPr = 1
	--	, okDi = 1
	--	, okQM = 1
	--	, okSc = 1
	
	--select distinct ProcessNum from ProductionLog
	--select top 10 * from ext.ProductionLogRaw

	---- fix errore packaging
	--update tmp.ProductionLogRaw 
	--SET CodPackag='4'
	--where CodPackag LIKE '%4%' and CodPackag <> '4'
	--select * from tmp.ProductionLogRaw where CodPackag LIKE '%4%' and CodPackag <> '4'

	--SELECT p.CodDies, CodItem, CodClient, CodPackag, p.* FROM ext.ProductionLogRaw AS p
	--LEFT JOIN dbo.DiesDet AS d ON p.CodDies = d.CodDies 
	--WHERE CodItem IS NULL

    -- ===========================
	-- parte CALCOLI!!!
    -- ===========================

    TRUNCATE TABLE [dbo].[QuoteWorkInt]
    TRUNCATE TABLE [dbo].[QuoteWorkExt]
    TRUNCATE TABLE [dbo].QuoteParam
    TRUNCATE TABLE [dbo].QuoteOC
    TRUNCATE TABLE [dbo].[QuoteFull_Q]

    --TRUNCATE TABLE [dbo].QuoteRM  -- controllare prima di cancellare
    --DELETE FROM QuoteList

	SELECT * FROM QuoteList
    SELECT TOP 1000 * FROM QuoteRM

	--select * from ClientDet where CodClient='05000001048'
	--select * from itemdet
	--where CodItem like '1PT00102%'

	select * from RawMatDet

	--Q	1312130001	0	05000001048	1PT00102	A	7020	7673,400	1000	CPT	NULL	NULL	NULL	NULL

	SELECT	--TOP 10 
			 dd.CodItem, pl.RawMat, dd.CodItem + '-' + pl.RawMat as KeyAM, dd.CodDiesGroup, pl.CodPlant, dd.HoleNum
			,dd.CodItem + '-' + pl.RawMat + '-' + pl.CodPlant + '-' + CAST(dd.HoleNum AS NVARCHAR(19)) as KeyAMIL
			,0 as NumSMED -- numero cambi, da sistemare...
			, SUM(QtyOUT) as KgTeorici, SUM(Duration) AS Durata
			,ISNULL(SUM(QtyOUT),0)/ISNULL(SUM(Duration), 1) as ProduttTeo
	FROM	ProductionLog pl INNER JOIN DiesDet dd ON pl.CodDies=dd.CodDies
	WHERE	pl.ProcessNum='01' and pl.EventType=1
	GROUP BY dd.CodItem, pl.RawMat, dd.CodDiesGroup, pl.CodPlant, dd.HoleNum
	ORDER BY dd.CodItem, pl.RawMat, dd.CodDiesGroup, SUM(QtyOUT) DESC

    -- ==========================================
	-- re-insert dei dati di produzione x statistiche
    -- ==========================================
    --DECLARE @dateFrom AS DateTime;
    --DECLARE @dateTo   AS DateTime;
    --SET @dateFrom = '20100101' 
    --SET @dateTo   = '20130929'

	exec stp_TPS_upsert @dateFrom, @dateTo
	exec stp_TD_upsert @dateFrom , @dateTo
--	exec stp_TI_upsert @dateFrom , @dateTo   -- adesso sono già calcolati e inseriti in Package2 / Package2Item

    SELECT TOP 1000 * FROM TabProdSc
    SELECT TOP 1000 * FROM TabDifett

    -- ==========================================
	-- salvo nuova revisione dati di produzione...
    -- Va messa in ogni procedura di update con 'procedura' e versione anno-mese-giorno
    -- ==========================================
	--INSERT INTO RevHistory
	--SELECT	'P', ISNULL(MAX(RevNum),0) + 1, GETDATE(), 'Aggiornamento dati di produzione x fase 04 ' + CONVERT(NVARCHAR(20), @dateFrom, 120) + ' --> ' +CONVERT(NVARCHAR(20), @dateTo, 120)
	--FROM	RevHistory
	--WHERE	RevType = 'P' 
 --   AND RevNum = 1        -- mod. 14/05 GCARLO altrimenti ne crea una per ogni riga di RevHistory

	--select * from RevHistory

	-- simulazione tempo di calcolo: circa 50/sec
	---- aggiornamento dei dati dell'offerta in oggetto
	--DECLARE @tick DATETIME,
	--		@idx INT = 100
	--SET @tick = GETDATE()
	--WHILE @idx > 0
	--BEGIN
	--	EXEC stp_QL_update 'Q', 1312130001, 0
	--	SELECT @idx = @idx - 1
	--END
	--SELECT GETDATE() - @tick as tempo

/*
    ARRIVATO QUI - da errore la funzione f_getSubstring perchè ritorna NULL al posto di '' ??? riga della stored 295 dovuto a trasformazione dei gruppi Dies - sistemato
*/

    -- prima aggiorno i dati di Cost2Plant che non si sa da dove arrivano ( caricati a mano??? )

    SELECT TOP 1000 * FROM Cost2Plant
    SELECT TOP 1000 * FROM C2P.dbo.Cost2Plant
    SELECT * from TrascPlan

    DELETE FROM Cost2Plant

    INSERT INTO Cost2Plant
    SELECT  t.CodPlantNew, ProcessNum, FC, VC, OH, SC, QuotaPlantStd, QuotaManStd 
    FROM C2P.dbo.Cost2Plant AS cp
    LEFT JOIN TrascPlan AS t ON cp.CodPlant = t.CodPlant

    -- GCARLO DEVO creare la riga per il test, la copio da quella di sviluppo e agg. i dati di demo
    SELECT TOP 1000 * FROM QuoteList
    SELECT TOP 1000 * FROM QuoteRM
    SELECT TOP 1000 * FROM C2P.dbo.QuoteList
    SELECT TOP 1000 * FROM C2P.dbo.QuoteRM WHERE CodQuote = '1402050001'

    -- creo righe di test
    INSERT QuoteList
    SELECT QuoteType, CodQuote, QuoteRev, IdxQState, CodClientNew, CodItemNew, CodItemGroup, RawMat, UnitWeight, BatchQty, CodInco, Note, PriceOff, OrdDate, OrdNum, OrdRow, OrdPrice, valid, errorScore 
    FROM   C2P.[dbo].[QuoteList] AS q
    INNER JOIN [dbo].[TrascClient] AS tc ON q.CodClient = tc.CodClient
    INNER JOIN dbo.TrascItem AS ti ON q.CodItem = ti.CodItem

    INSERT QuoteRM
    SELECT QuoteType, CodQuote, QuoteRev, NumRM, RawMat, RawMatCost, RawMatExtraCost, CodPackag, FCR, valid 
    FROM C2P.[dbo].[QuoteRM]

    UPDATE QuoteList
      SET  CodClient = ( SELECT CodClientNew FROM TrascClient WHERE CodClient = '05000000382' )
          ,CodItem   = ( SELECT CodItemNew FROM TrascItem   WHERE CodItem = '3DI05376' )
    WHERE CodQuote = '1402050001'

    -- *** ESEGUO L'AGGIORNAMENTO **** 

	DECLARE @QuoteType	CHAR(1)       = 'Q',
			@CodQuote	BIGINT	      = 1402050001,
			@QuoteRev	INT		      = 0,
            @PriceOff   DECIMAL(9, 6) = 0

    -- EXEC stp_QL_update 'Q', 1402050001, 0   -- <<<<< ERRORE
    -- EXECUTE dbo.stp_QuoteFull_Q_update 'Q', 1402050001, 0, 0.1  -- crea il record in QuoteFull_Q

	EXEC stp_QL_update @QuoteType, @CodQuote, @QuoteRev
    SELECT @PriceOff = PriceOff FROM QuoteList WHERE CodQuote= @CodQuote AND QuoteRev = @QuoteRev
    EXECUTE dbo.stp_QuoteFull_Q_update @QuoteType, @CodQuote, @QuoteRev  -- crea il record in QuoteFull_Q

	SELECT	* FROM	QuoteList    WHERE QuoteType=@QuoteType AND CodQuote = @CodQuote AND  QuoteRev = @QuoteRev
	SELECT	* FROM	QuoteRM      WHERE QuoteType=@QuoteType AND CodQuote = @CodQuote AND  QuoteRev = @QuoteRev
	SELECT	* FROM	QuoteWorkInt WHERE QuoteType=@QuoteType AND CodQuote = @CodQuote AND  QuoteRev = @QuoteRev
	SELECT	* FROM	QuoteWorkExt WHERE QuoteType=@QuoteType AND CodQuote = @CodQuote AND  QuoteRev = @QuoteRev
	SELECT	* FROM	QuoteOC      WHERE QuoteType=@QuoteType AND CodQuote = @CodQuote AND  QuoteRev = @QuoteRev
	SELECT	* FROM	QuoteParam   WHERE QuoteType=@QuoteType AND CodQuote = @CodQuote AND  QuoteRev = @QuoteRev
    
	select top 10 * from ItemDet

	SELECT	* FROM	RawMatDet
	
	SELECT	top 10	* FROM TabProdSc
	SELECT	top 10	* FROM TabDifett
--	SELECT			* FROM TabImbArt
--	SELECT			* FROM TabImbGrp
	SELECT			* FROM PackagDet
	SELECT			* FROM Package2

	---- test gestione selezione CodPackag corretto
	--SELECT TOP 5 * FROM Package2ItemClient
	--SELECT TOP 5 * FROM Package2Item
	--SELECT TOP 5 * FROM Package2

	-- SELECT dbo.f_getCodPackag('1EL00005', '05000001048')
	--SELECT dbo.f_getCodPackag('1AN00001', '05000000137')
	
	
END
GO
PRINT N'Creating [dbo].[QuoteOC].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Altri costi (diretti-indiretti)', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteOC';


GO
PRINT N'Creating [dbo].[QuoteOC].[QuoteType].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'tipo di preventivo: Q = quote, S = simulation', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteOC', @level2type = N'COLUMN', @level2name = N'QuoteType';


GO
PRINT N'Creating [dbo].[QuoteOC].[CodQuote].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'numero nel formato yyMMddnnnn dove nnn è incrementale giornaliero', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteOC', @level2type = N'COLUMN', @level2name = N'CodQuote';


GO
PRINT N'Creating [dbo].[QuoteOC].[NumEx].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'progressivo del costo OTHER', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteOC', @level2type = N'COLUMN', @level2name = N'NumEx';


GO
PRINT N'Creating [dbo].[QuoteOC].[ProcessNum].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Tipo risorsa (e lavorazione): 01 .. 04', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteOC', @level2type = N'COLUMN', @level2name = N'ProcessNum';


GO
PRINT N'Creating [dbo].[QuoteOC].[CodPlant].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'codice impianto', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteOC', @level2type = N'COLUMN', @level2name = N'CodPlant';


GO
PRINT N'Creating [dbo].[QuoteOC].[Class01].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Riclass. 01, tipo di costo :
- UTIL (EE/GAS)
- ROTTAME (costo rifusione + quota perdita x ri-vendita)
- CONS 
- TRASP 
- PROVV 
- EXTRA', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteOC', @level2type = N'COLUMN', @level2name = N'Class01';


GO
PRINT N'Creating [dbo].[QuoteOC].[Class02].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Riclass. 02, codice di ricerca per tipo di costo extra, es se consumabili è codice matrice', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteOC', @level2type = N'COLUMN', @level2name = N'Class02';


GO
PRINT N'Creating [dbo].[QuoteOC].[Class03].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Riclass. 03', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteOC', @level2type = N'COLUMN', @level2name = N'Class03';


GO
PRINT N'Creating [dbo].[QuoteOC].[Class04].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Riclass. 04', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteOC', @level2type = N'COLUMN', @level2name = N'Class04';


GO
PRINT N'Creating [dbo].[QuoteOC].[Class05].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Riclass. 05', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteOC', @level2type = N'COLUMN', @level2name = N'Class05';


GO
PRINT N'Creating [dbo].[QuoteOC].[TotQty].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'quantità totale di riferimento', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteOC', @level2type = N'COLUMN', @level2name = N'TotQty';


GO
PRINT N'Creating [dbo].[QuoteOC].[TotCost].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Costo totale di riferimento', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteOC', @level2type = N'COLUMN', @level2name = N'TotCost';


GO
PRINT N'Creating [dbo].[QuoteOC].[Quota].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Quota di impiego', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteOC', @level2type = N'COLUMN', @level2name = N'Quota';


GO
PRINT N'Creating [dbo].[QuoteOC].[C4UG].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Costo pro quota di impiego (per matrici, imballi,...)', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteOC', @level2type = N'COLUMN', @level2name = N'C4UG';


GO
PRINT N'Creating [dbo].[QuoteWorkExt].[QuoteType].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'tipo di preventivo: Q = quote, S = simulation', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteWorkExt', @level2type = N'COLUMN', @level2name = N'QuoteType';


GO
PRINT N'Creating [dbo].[QuoteWorkExt].[CodQuote].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'numero nel formato yyMMddnnnn dove nnn è incrementale giornaliero', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteWorkExt', @level2type = N'COLUMN', @level2name = N'CodQuote';


GO
PRINT N'Creating [dbo].[QuoteWorkExt].[NumWE].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'progressivo interno', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteWorkExt', @level2type = N'COLUMN', @level2name = N'NumWE';


GO
PRINT N'Creating [dbo].[QuoteWorkExt].[EWC4UG].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'External Work Cost FOR Unit of Good, quota dei costi fissi per unità di prodotto finito (Copertura Costo Struttura e Linea)', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteWorkExt', @level2type = N'COLUMN', @level2name = N'EWC4UG';


GO
PRINT N'Creating [dbo].[QuoteWorkExt].[UM].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Unità di misura di riferimento per il costo', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteWorkExt', @level2type = N'COLUMN', @level2name = N'UM';


GO
PRINT N'Creating [dbo].[Package2Item].[CodItem].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'codice articolo', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'Package2Item', @level2type = N'COLUMN', @level2name = N'CodItem';


GO
PRINT N'Creating [dbo].[Package2Item].[TotQta].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Quantità totale lavorata', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'Package2Item', @level2type = N'COLUMN', @level2name = N'TotQta';


GO
PRINT N'Creating [dbo].[Package2Item].[Weight].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Peso medio', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'Package2Item', @level2type = N'COLUMN', @level2name = N'Weight';


GO
PRINT N'Creating [dbo].[Package2Item].[Tare].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Tara', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'Package2Item', @level2type = N'COLUMN', @level2name = N'Tare';


GO
PRINT N'Creating [dbo].[Package2ItemClient].[CodItem].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'codice articolo', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'Package2ItemClient', @level2type = N'COLUMN', @level2name = N'CodItem';


GO
PRINT N'Creating [dbo].[Package2ItemClient].[CodClient].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'codice cliente', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'Package2ItemClient', @level2type = N'COLUMN', @level2name = N'CodClient';


GO
PRINT N'Creating [dbo].[Package2ItemClient].[TotQta].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Quantità totale lavorata', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'Package2ItemClient', @level2type = N'COLUMN', @level2name = N'TotQta';


GO
PRINT N'Creating [dbo].[Package2ItemClient].[Weight].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Peso medio', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'Package2ItemClient', @level2type = N'COLUMN', @level2name = N'Weight';


GO
PRINT N'Creating [dbo].[Package2ItemClient].[Tare].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Tara', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'Package2ItemClient', @level2type = N'COLUMN', @level2name = N'Tare';


GO
PRINT N'Creating [dbo].[PackagDet].[RMCost].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Raw Material Cost - costo dei materiali', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'PackagDet', @level2type = N'COLUMN', @level2name = N'RMCost';


GO
PRINT N'Creating [dbo].[PackagDet].[RMWeight].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'kg peso medio', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'PackagDet', @level2type = N'COLUMN', @level2name = N'RMWeight';


GO
PRINT N'Creating [dbo].[PlantsDet].[CodPlant].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'codice impianto', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'PlantsDet', @level2type = N'COLUMN', @level2name = N'CodPlant';


GO
PRINT N'Creating [dbo].[PlantsDet].[Descript].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'descrizione impianto', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'PlantsDet', @level2type = N'COLUMN', @level2name = N'Descript';


GO
PRINT N'Creating [dbo].[PlantsDet].[Charge].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Over Head costo €/h per CDC + FASE', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'PlantsDet', @level2type = N'COLUMN', @level2name = N'Charge';


GO
PRINT N'Creating [dbo].[RevHistory].[RevType].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Tipo di revisione indicata coem S.C.P --> in C = costi di contab industriale, P = da ProductionLog, S = Sistema di calcolo', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'RevHistory', @level2type = N'COLUMN', @level2name = N'RevType';


GO
PRINT N'Creating [dbo].[RevHistory].[RevNum].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'incrementale del numero di revisione', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'RevHistory', @level2type = N'COLUMN', @level2name = N'RevNum';


GO
PRINT N'Creating [dbo].[RevHistory].[DateRev].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'data revisione', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'RevHistory', @level2type = N'COLUMN', @level2name = N'DateRev';


GO
PRINT N'Creating [dbo].[RevHistory].[Description].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'descrizione revisione', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'RevHistory', @level2type = N'COLUMN', @level2name = N'Description';


GO
PRINT N'Creating [dbo].[DiesGroupDet].[CodDiesGroup].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'codice CLASSE matrice, es tipo + diametro', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'DiesGroupDet', @level2type = N'COLUMN', @level2name = N'CodDiesGroup';


GO
PRINT N'Creating [dbo].[DiesGroupDet].[Price].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'prezzo di acquisto', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'DiesGroupDet', @level2type = N'COLUMN', @level2name = N'Price';


GO
PRINT N'Creating [dbo].[DiesGroupDet].[QtyTot].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Totale matrici del gruppo', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'DiesGroupDet', @level2type = N'COLUMN', @level2name = N'QtyTot';


GO
PRINT N'Creating [dbo].[DiesGroupDet].[QtyEOL].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'numero rottamate nel gruppo (End Of Life)', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'DiesGroupDet', @level2type = N'COLUMN', @level2name = N'QtyEOL';


GO
PRINT N'Creating [dbo].[DiesGroupDet].[ExpLife].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Durata attesa in kg PREVISTA', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'DiesGroupDet', @level2type = N'COLUMN', @level2name = N'ExpLife';


GO
PRINT N'Creating [dbo].[DiesGroupDet].[EOLLife].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Durata attuale (delle rottamate, media) in kg', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'DiesGroupDet', @level2type = N'COLUMN', @level2name = N'EOLLife';


GO
PRINT N'Creating [dbo].[Cost2Plant].[CodPlant].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'codice impianto', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'Cost2Plant', @level2type = N'COLUMN', @level2name = N'CodPlant';


GO
PRINT N'Creating [dbo].[Cost2Plant].[ProcessNum].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'codice fase, da qui si crea anagrafica fasi distinct', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'Cost2Plant', @level2type = N'COLUMN', @level2name = N'ProcessNum';


GO
PRINT N'Creating [dbo].[Cost2Plant].[FC].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Costo Fissi €/h per CDC + FASE', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'Cost2Plant', @level2type = N'COLUMN', @level2name = N'FC';


GO
PRINT N'Creating [dbo].[Cost2Plant].[VC].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Costi Variabili €/h per CDC + FASE', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'Cost2Plant', @level2type = N'COLUMN', @level2name = N'VC';


GO
PRINT N'Creating [dbo].[Cost2Plant].[OH].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Over Head costo €/h per CDC + FASE', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'Cost2Plant', @level2type = N'COLUMN', @level2name = N'OH';


GO
PRINT N'Creating [dbo].[Cost2Plant].[SC].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'costoSETUP €/cambio per CDC + FASE', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'Cost2Plant', @level2type = N'COLUMN', @level2name = N'SC';


GO
PRINT N'Creating [dbo].[Cost2Plant].[QuotaPlantStd].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'indicazione della quota macchina per produrre quanto registrato', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'Cost2Plant', @level2type = N'COLUMN', @level2name = N'QuotaPlantStd';


GO
PRINT N'Creating [dbo].[Cost2Plant].[QuotaManStd].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'indicazione della quota uomo per produrre quanto registrato', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'Cost2Plant', @level2type = N'COLUMN', @level2name = N'QuotaManStd';


GO
PRINT N'Creating [dbo].[ClientDet].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Client Details Table', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'ClientDet';


GO
PRINT N'Creating [dbo].[ClientDet].[CodClient].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'codice cliente', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'ClientDet', @level2type = N'COLUMN', @level2name = N'CodClient';


GO
PRINT N'Creating [dbo].[ClientDet].[ClientName].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Ragione Sociale', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'ClientDet', @level2type = N'COLUMN', @level2name = N'ClientName';


GO
PRINT N'Creating [dbo].[ClientDet].[CodAg].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'codice agente...', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'ClientDet', @level2type = N'COLUMN', @level2name = N'CodAg';


GO
PRINT N'Creating [dbo].[ClientDet].[ZipCode].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'cap', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'ClientDet', @level2type = N'COLUMN', @level2name = N'ZipCode';


GO
PRINT N'Creating [dbo].[ClientDet].[City].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'città', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'ClientDet', @level2type = N'COLUMN', @level2name = N'City';


GO
PRINT N'Creating [dbo].[ClientDet].[State].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'stato/provincia', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'ClientDet', @level2type = N'COLUMN', @level2name = N'State';


GO
PRINT N'Creating [dbo].[ClientDet].[Nation].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'nazione', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'ClientDet', @level2type = N'COLUMN', @level2name = N'Nation';


GO
PRINT N'Creating [dbo].[ClientDet].[TranspZone].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Classificazione cliente (es zona, provincia...) x incrocio con tab costi trasporto', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'ClientDet', @level2type = N'COLUMN', @level2name = N'TranspZone';


GO
PRINT N'Creating [dbo].[AgentsDet].[CodAg].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'codice agente...', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'AgentsDet', @level2type = N'COLUMN', @level2name = N'CodAg';


GO
PRINT N'Creating [dbo].[AgentsDet].[Lastname].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Cognome', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'AgentsDet', @level2type = N'COLUMN', @level2name = N'Lastname';


GO
PRINT N'Creating [dbo].[AgentsDet].[Firstname].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Nome', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'AgentsDet', @level2type = N'COLUMN', @level2name = N'Firstname';


GO
PRINT N'Creating [dbo].[AgentsDet].[QuotaProvvAg].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Provvigione come €/kg', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'AgentsDet', @level2type = N'COLUMN', @level2name = N'QuotaProvvAg';


GO
PRINT N'Creating [dbo].[Utilities].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'costo unitario per unità di PF (€/kg)', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'Utilities';


GO
PRINT N'Creating [dbo].[Utilities].[CodUtil].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'codice dell''utility (Energia elettrica / gas)', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'Utilities', @level2type = N'COLUMN', @level2name = N'CodUtil';


GO
PRINT N'Creating [dbo].[Utilities].[CodPlant].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'codice impianto', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'Utilities', @level2type = N'COLUMN', @level2name = N'CodPlant';


GO
PRINT N'Creating [dbo].[Utilities].[UnitCost].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Costo al kg per impianto ed utility', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'Utilities', @level2type = N'COLUMN', @level2name = N'UnitCost';


GO
PRINT N'Creating [dbo].[Incoterms].[CodInco].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Codice Incoterms', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'Incoterms', @level2type = N'COLUMN', @level2name = N'CodInco';


GO
PRINT N'Creating [dbo].[Incoterms].[Descript].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Descrizione Incoterms', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'Incoterms', @level2type = N'COLUMN', @level2name = N'Descript';


GO
PRINT N'Creating [dbo].[Incoterms].[HasTC].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Indica se ha costi di trasporto (1) o non lil ha (0)', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'Incoterms', @level2type = N'COLUMN', @level2name = N'HasTC';


GO
PRINT N'Creating [dbo].[TranspCostDet].[TranspZone].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Classificazione cliente (es zona, provincia...) x incrocio con tab costi trasporto', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'TranspCostDet', @level2type = N'COLUMN', @level2name = N'TranspZone';


GO
PRINT N'Creating [dbo].[TranspCostDet].[TranspCost].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'costi di traporto €/kg', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'TranspCostDet', @level2type = N'COLUMN', @level2name = N'TranspCost';


GO
PRINT N'Creating [dbo].[QuoteRM].[QuoteType].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'tipo di preventivo: Q = quote, S = simulation', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteRM', @level2type = N'COLUMN', @level2name = N'QuoteType';


GO
PRINT N'Creating [dbo].[QuoteRM].[CodQuote].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'numero nel formato yyMMddnnnn dove nnn è incrementale giornaliero', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteRM', @level2type = N'COLUMN', @level2name = N'CodQuote';


GO
PRINT N'Creating [dbo].[QuoteRM].[NumRM].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'progressivo interno', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteRM', @level2type = N'COLUMN', @level2name = N'NumRM';


GO
PRINT N'Creating [dbo].[QuoteRM].[RawMat].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'codice MP', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteRM', @level2type = N'COLUMN', @level2name = N'RawMat';


GO
PRINT N'Creating [dbo].[QuoteRM].[RawMatCost].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'costo della MP €/kg', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteRM', @level2type = N'COLUMN', @level2name = N'RawMatCost';


GO
PRINT N'Creating [dbo].[QuoteRM].[RawMatExtraCost].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'costo degli extra della MP €/kg', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteRM', @level2type = N'COLUMN', @level2name = N'RawMatExtraCost';


GO
PRINT N'Creating [dbo].[QuoteRM].[FCR].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Tasso di conversione TOTALE, messa al cento, quantità di MP necessaria per produrre un unità di prodotto', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteRM', @level2type = N'COLUMN', @level2name = N'FCR';


GO
PRINT N'Creating [dbo].[QuoteRM].[FYR].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'FULL Yield Ratio, percentuale RESA TOTALE', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteRM', @level2type = N'COLUMN', @level2name = N'FYR';


GO
PRINT N'Creating [dbo].[QuoteRM].[FSR].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'FULL Scrape Ratio, percentuale scarto TOTALE', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteRM', @level2type = N'COLUMN', @level2name = N'FSR';


GO
PRINT N'Creating [dbo].[ItemDet].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Item Details Table', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'ItemDet';


GO
PRINT N'Creating [dbo].[ItemDet].[CodItem].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'codice articolo', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'ItemDet', @level2type = N'COLUMN', @level2name = N'CodItem';


GO
PRINT N'Creating [dbo].[ItemDet].[UnitWeight].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'peso espresso come g/m (grammi / metro)', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'ItemDet', @level2type = N'COLUMN', @level2name = N'UnitWeight';


GO
PRINT N'Creating [dbo].[ItemDet].[CodItemGroup].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'classe raggruppamento (es complessità disegno)', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'ItemDet', @level2type = N'COLUMN', @level2name = N'CodItemGroup';


GO
PRINT N'Creating [dbo].[ItemDet].[Class01].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'ItemDet', @level2type = N'COLUMN', @level2name = N'Class01';


GO
PRINT N'Creating [dbo].[v_selClient].[MS_DiagramPane1]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_DiagramPane1', @value = N'[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 = "ClientDet"
            Begin Extent = 
               Top = 6
               Left = 38
               Bottom = 258
               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 = 11790
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
      End
   End
   Begin CriteriaPane = 
      Begin ColumnWidths = 11
         Column = 1440
         Alias = 900
         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
', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'VIEW', @level1name = N'v_selClient';


GO
PRINT N'Creating [dbo].[v_selClient].[MS_DiagramPaneCount]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_DiagramPaneCount', @value = 1, @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'VIEW', @level1name = N'v_selClient';


GO
PRINT N'Creating [dbo].[Package2].[TotQta].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Quantità totale lavorata', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'Package2', @level2type = N'COLUMN', @level2name = N'TotQta';


GO
PRINT N'Creating [dbo].[Package2].[Weight].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Peso medio', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'Package2', @level2type = N'COLUMN', @level2name = N'Weight';


GO
PRINT N'Creating [dbo].[Package2].[Tare].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Tara', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'Package2', @level2type = N'COLUMN', @level2name = N'Tare';


GO
PRINT N'Creating [dbo].[v_selIncoterms].[MS_DiagramPaneCount]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_DiagramPaneCount', @value = 1, @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'VIEW', @level1name = N'v_selIncoterms';


GO
PRINT N'Creating [dbo].[v_selIncoterms].[MS_DiagramPane1]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_DiagramPane1', @value = N'[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 = "Incoterms"
            Begin Extent = 
               Top = 6
               Left = 38
               Bottom = 119
               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 = 5055
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
      End
   End
   Begin CriteriaPane = 
      Begin ColumnWidths = 11
         Column = 1440
         Alias = 900
         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
', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'VIEW', @level1name = N'v_selIncoterms';


GO
PRINT N'Creating [dbo].[v_selCons].[MS_DiagramPaneCount]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_DiagramPaneCount', @value = 1, @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'VIEW', @level1name = N'v_selCons';


GO
PRINT N'Creating [dbo].[v_selCons].[MS_DiagramPane1]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_DiagramPane1', @value = N'[0E232FF0-B466-11cf-A24F-00AA00A3EFFF, 1.00]
Begin DesignProperties = 
   Begin PaneConfigurations = 
      Begin PaneConfiguration = 0
         NumPanes = 4
         Configuration = "(H (1[41] 4[20] 2[10] 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 = "Incoterms"
            Begin Extent = 
               Top = 6
               Left = 38
               Bottom = 119
               Right = 208
            End
            DisplayFlags = 280
            TopColumn = 0
         End
      End
   End
   Begin SQLPane = 
   End
   Begin DataPane = 
      Begin ParameterDefaults = ""
      End
      Begin ColumnWidths = 9
         Width = 284
         Width = 840
         Width = 4620
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
      End
   End
   Begin CriteriaPane = 
      Begin ColumnWidths = 11
         Column = 1440
         Alias = 900
         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
', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'VIEW', @level1name = N'v_selCons';


GO
PRINT N'Creating [dbo].[DiesDet].[CodDies].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'codice matrice', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'DiesDet', @level2type = N'COLUMN', @level2name = N'CodDies';


GO
PRINT N'Creating [dbo].[DiesDet].[CodItem].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'codice articolo', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'DiesDet', @level2type = N'COLUMN', @level2name = N'CodItem';


GO
PRINT N'Creating [dbo].[DiesDet].[CodDiesGroup].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'codice CLASSE matrice, es tipo + diametro; nota: massima numerosità pari a numero articoli, minima numerosità 1', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'DiesDet', @level2type = N'COLUMN', @level2name = N'CodDiesGroup';


GO
PRINT N'Creating [dbo].[DiesDet].[Price].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'prezzo di acquisto', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'DiesDet', @level2type = N'COLUMN', @level2name = N'Price';


GO
PRINT N'Creating [dbo].[DiesDet].[TestCost].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'costo di prove e correzioni', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'DiesDet', @level2type = N'COLUMN', @level2name = N'TestCost';


GO
PRINT N'Creating [dbo].[DiesDet].[ExpLife].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Durata attesa in kg PREVISTA', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'DiesDet', @level2type = N'COLUMN', @level2name = N'ExpLife';


GO
PRINT N'Creating [dbo].[DiesDet].[ActLife].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Durata attuale (delle rottamate, media) in kg', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'DiesDet', @level2type = N'COLUMN', @level2name = N'ActLife';


GO
PRINT N'Creating [dbo].[DiesDet].[Active].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Stato: 1 = disponibile, 0 = rottamata', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'DiesDet', @level2type = N'COLUMN', @level2name = N'Active';


GO
PRINT N'Creating [dbo].[ProductionLog].[EventStart].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'inizio evento - formato INT 16 cifre yyyyMMddHHmmssnn dove nn = centesimi di sec oppure 00', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'ProductionLog', @level2type = N'COLUMN', @level2name = N'EventStart';


GO
PRINT N'Creating [dbo].[ProductionLog].[EventEnd].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'fine evento - formato INT 16 cifre yyyyMMddHHmmssnn dove nn = centesimi di sec oppure 00', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'ProductionLog', @level2type = N'COLUMN', @level2name = N'EventEnd';


GO
PRINT N'Creating [dbo].[ProductionLog].[CodPlant].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'codice impianto', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'ProductionLog', @level2type = N'COLUMN', @level2name = N'CodPlant';


GO
PRINT N'Creating [dbo].[ProductionLog].[ProcessNum].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'codice fase, da qui si crea anagrafica fasi distinct', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'ProductionLog', @level2type = N'COLUMN', @level2name = N'ProcessNum';


GO
PRINT N'Creating [dbo].[ProductionLog].[CodDies].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'codice matrice', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'ProductionLog', @level2type = N'COLUMN', @level2name = N'CodDies';


GO
PRINT N'Creating [dbo].[ProductionLog].[CodClient].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'codice cliente', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'ProductionLog', @level2type = N'COLUMN', @level2name = N'CodClient';


GO
PRINT N'Creating [dbo].[ProductionLog].[OrderNum].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'rif codice ordine', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'ProductionLog', @level2type = N'COLUMN', @level2name = N'OrderNum';


GO
PRINT N'Creating [dbo].[ProductionLog].[BatchNum].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'codice lotto', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'ProductionLog', @level2type = N'COLUMN', @level2name = N'BatchNum';


GO
PRINT N'Creating [dbo].[ProductionLog].[ProcessType].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'codice del TIPO di fase, x raggruppamento funzionale', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'ProductionLog', @level2type = N'COLUMN', @level2name = N'ProcessType';


GO
PRINT N'Creating [dbo].[ProductionLog].[EventType].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'tipo evento: produzione, prova, guasto, setup...', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'ProductionLog', @level2type = N'COLUMN', @level2name = N'EventType';


GO
PRINT N'Creating [dbo].[ProductionLog].[RawMat].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'codice MP', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'ProductionLog', @level2type = N'COLUMN', @level2name = N'RawMat';


GO
PRINT N'Creating [dbo].[ProductionLog].[CodPackag].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'codice imballo', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'ProductionLog', @level2type = N'COLUMN', @level2name = N'CodPackag';


GO
PRINT N'Creating [dbo].[ProductionLog].[QtyIN].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'kg materiale in ingresso', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'ProductionLog', @level2type = N'COLUMN', @level2name = N'QtyIN';


GO
PRINT N'Creating [dbo].[ProductionLog].[QtyOUT].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'kg materiale BUONO prodotto in OUTput', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'ProductionLog', @level2type = N'COLUMN', @level2name = N'QtyOUT';


GO
PRINT N'Creating [dbo].[ProductionLog].[QtyEXT].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'kg materiale dbora che fa parte dell''OUT, es imballi/tara', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'ProductionLog', @level2type = N'COLUMN', @level2name = N'QtyEXT';


GO
PRINT N'Creating [dbo].[ProductionLog].[NumIN].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'qta materiale in ingresso', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'ProductionLog', @level2type = N'COLUMN', @level2name = N'NumIN';


GO
PRINT N'Creating [dbo].[ProductionLog].[NumOUT].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'qta materiale BUONO prodotto in OUTput', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'ProductionLog', @level2type = N'COLUMN', @level2name = N'NumOUT';


GO
PRINT N'Creating [dbo].[ProductionLog].[QuotaPlant].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'indicazione della quota macchina per produrre quanto registrato', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'ProductionLog', @level2type = N'COLUMN', @level2name = N'QuotaPlant';


GO
PRINT N'Creating [dbo].[ProductionLog].[QuotaMan].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'indicazione della quota uomo per produrre quanto registrato', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'ProductionLog', @level2type = N'COLUMN', @level2name = N'QuotaMan';


GO
PRINT N'Creating [dbo].[ProductionLog].[Tags].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'categorie LIBERE, separatore #', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'ProductionLog', @level2type = N'COLUMN', @level2name = N'Tags';


GO
PRINT N'Creating [dbo].[ProductionLog].[Duration].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Durata espressa in ore', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'ProductionLog', @level2type = N'COLUMN', @level2name = N'Duration';


GO
PRINT N'Creating [dbo].[ProductionLog].[okPr].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'validazione riga x calcolo produttività', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'ProductionLog', @level2type = N'COLUMN', @level2name = N'okPr';


GO
PRINT N'Creating [dbo].[ProductionLog].[okQM].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'validazione riga x calcolo quota MAN', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'ProductionLog', @level2type = N'COLUMN', @level2name = N'okQM';


GO
PRINT N'Creating [dbo].[ProductionLog].[okSc].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'validazione riga x calcolo scarti', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'ProductionLog', @level2type = N'COLUMN', @level2name = N'okSc';


GO
PRINT N'Creating [dbo].[ProductionLog].[okDi].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'validazione riga x calcolo difettosità', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'ProductionLog', @level2type = N'COLUMN', @level2name = N'okDi';


GO
PRINT N'Creating [dbo].[QuoteFull_Q].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Quotation', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteFull_Q';


GO
PRINT N'Creating [dbo].[QuoteFull_Q].[IdxQState].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Stato offerta: 0 = D raft, 1 = C ompleted / in approvazione, 2 = A pprouved, 3 = R eleased', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteFull_Q', @level2type = N'COLUMN', @level2name = N'IdxQState';


GO
PRINT N'Creating [dbo].[QuoteFull_Q].[TranspZone].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Classificazione cliente (es zona, provincia...) x incrocio con tab costi trasporto', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteFull_Q', @level2type = N'COLUMN', @level2name = N'TranspZone';


GO
PRINT N'Creating [dbo].[QuoteFull_Q].[PriceOff].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Prezzo Offerto', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteFull_Q', @level2type = N'COLUMN', @level2name = N'PriceOff';


GO
PRINT N'Creating [dbo].[QuoteFull_Q].[errorScore].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'punteggio complessivo errori in procedure di calcolo', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteFull_Q', @level2type = N'COLUMN', @level2name = N'errorScore';


GO
PRINT N'Creating [dbo].[QuoteList].[QuoteType].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'tipo di preventivo: Q = quote, S = simulation', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteList', @level2type = N'COLUMN', @level2name = N'QuoteType';


GO
PRINT N'Creating [dbo].[QuoteList].[CodQuote].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'numero nel formato yyMMddnnnn dove nnn è incrementale giornaliero', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteList', @level2type = N'COLUMN', @level2name = N'CodQuote';


GO
PRINT N'Creating [dbo].[QuoteList].[IdxQState].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Stato offerta: 0 = D raft, 1 = C ompleted / in approvazione, 2 = A pprouved, 3 = R eleased', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteList', @level2type = N'COLUMN', @level2name = N'IdxQState';


GO
PRINT N'Creating [dbo].[QuoteList].[CodClient].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'codice cliente', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteList', @level2type = N'COLUMN', @level2name = N'CodClient';


GO
PRINT N'Creating [dbo].[QuoteList].[CodItem].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'codice articolo', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteList', @level2type = N'COLUMN', @level2name = N'CodItem';


GO
PRINT N'Creating [dbo].[QuoteList].[CodItemGroup].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'classe raggruppamento (es complessità disegno)', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteList', @level2type = N'COLUMN', @level2name = N'CodItemGroup';


GO
PRINT N'Creating [dbo].[QuoteList].[RawMat].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'codice MP', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteList', @level2type = N'COLUMN', @level2name = N'RawMat';


GO
PRINT N'Creating [dbo].[QuoteList].[UnitWeight].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'peso espresso come g/m (grammi / metro)', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteList', @level2type = N'COLUMN', @level2name = N'UnitWeight';


GO
PRINT N'Creating [dbo].[QuoteList].[BatchQty].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Quantità lotto kg', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteList', @level2type = N'COLUMN', @level2name = N'BatchQty';


GO
PRINT N'Creating [dbo].[QuoteList].[CodInco].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Codice Incoterms', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteList', @level2type = N'COLUMN', @level2name = N'CodInco';


GO
PRINT N'Creating [dbo].[QuoteList].[PriceOff].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Prezzo Offerto', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteList', @level2type = N'COLUMN', @level2name = N'PriceOff';


GO
PRINT N'Creating [dbo].[QuoteList].[OrdDate].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'data dell''ordine', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteList', @level2type = N'COLUMN', @level2name = N'OrdDate';


GO
PRINT N'Creating [dbo].[QuoteList].[OrdNum].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'numero ordine', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteList', @level2type = N'COLUMN', @level2name = N'OrdNum';


GO
PRINT N'Creating [dbo].[QuoteList].[OrdRow].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'riga ordine', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteList', @level2type = N'COLUMN', @level2name = N'OrdRow';


GO
PRINT N'Creating [dbo].[QuoteList].[OrdPrice].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Prezzo finale ordine', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteList', @level2type = N'COLUMN', @level2name = N'OrdPrice';


GO
PRINT N'Creating [dbo].[QuoteList].[errorScore].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'punteggio complessivo errori in procedure di calcolo', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteList', @level2type = N'COLUMN', @level2name = N'errorScore';


GO
PRINT N'Creating [dbo].[QuoteParam].[QuoteType].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'tipo di preventivo: Q = quote, S = simulation', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteParam', @level2type = N'COLUMN', @level2name = N'QuoteType';


GO
PRINT N'Creating [dbo].[QuoteParam].[CodQuote].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'numero nel formato yyMMddnnnn dove nnn è incrementale giornaliero', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteParam', @level2type = N'COLUMN', @level2name = N'CodQuote';


GO
PRINT N'Creating [dbo].[QuoteParam].[NumP].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'progressivo interno', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteParam', @level2type = N'COLUMN', @level2name = N'NumP';


GO
PRINT N'Creating [dbo].[QuoteParam].[ProcessNum].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Tipo risorsa (e lavorazione): 01 .. 04', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteParam', @level2type = N'COLUMN', @level2name = N'ProcessNum';


GO
PRINT N'Creating [dbo].[QuoteWorkInt].[QuoteType].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'tipo di preventivo: Q = quote, S = simulation', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteWorkInt', @level2type = N'COLUMN', @level2name = N'QuoteType';


GO
PRINT N'Creating [dbo].[QuoteWorkInt].[CodQuote].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'numero nel formato yyMMddnnnn dove nnn è incrementale giornaliero', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteWorkInt', @level2type = N'COLUMN', @level2name = N'CodQuote';


GO
PRINT N'Creating [dbo].[QuoteWorkInt].[NumWI].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'progressivo interno', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteWorkInt', @level2type = N'COLUMN', @level2name = N'NumWI';


GO
PRINT N'Creating [dbo].[QuoteWorkInt].[ProcessNum].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Tipo risorsa (e lavorazione): estrusione/imballo', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteWorkInt', @level2type = N'COLUMN', @level2name = N'ProcessNum';


GO
PRINT N'Creating [dbo].[QuoteWorkInt].[CodPlant].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'codice impianto', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteWorkInt', @level2type = N'COLUMN', @level2name = N'CodPlant';


GO
PRINT N'Creating [dbo].[QuoteWorkInt].[Class01].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Riclass. 01, ARTICOLO + MATERIALE', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteWorkInt', @level2type = N'COLUMN', @level2name = N'Class01';


GO
PRINT N'Creating [dbo].[QuoteWorkInt].[Class02].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Riclass. 02, codice di ricerca per prod - es cod imballo o Chiave di ricerca Articolo/ClasseArt + RawMat+ Impianto + NumLuci', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteWorkInt', @level2type = N'COLUMN', @level2name = N'Class02';


GO
PRINT N'Creating [dbo].[QuoteWorkInt].[Class03].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Riclass. 03, tipo imballo', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteWorkInt', @level2type = N'COLUMN', @level2name = N'Class03';


GO
PRINT N'Creating [dbo].[QuoteWorkInt].[Class04].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Riclass. 04', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteWorkInt', @level2type = N'COLUMN', @level2name = N'Class04';


GO
PRINT N'Creating [dbo].[QuoteWorkInt].[Class05].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Riclass. 05', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteWorkInt', @level2type = N'COLUMN', @level2name = N'Class05';


GO
PRINT N'Creating [dbo].[QuoteWorkInt].[NetProd].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Produttivita netta (teorica) kg/h', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteWorkInt', @level2type = N'COLUMN', @level2name = N'NetProd';


GO
PRINT N'Creating [dbo].[QuoteWorkInt].[WSR].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Work Scrape Ratio, percentuale scarto della lavorazione (tecnico)', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteWorkInt', @level2type = N'COLUMN', @level2name = N'WSR';


GO
PRINT N'Creating [dbo].[QuoteWorkInt].[MSR].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Material Scrape Ratio, percentuale scarto legato alla MP (cesoia x alx)', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteWorkInt', @level2type = N'COLUMN', @level2name = N'MSR';


GO
PRINT N'Creating [dbo].[QuoteWorkInt].[DSR].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Defect Scrape Ratio, percentuale scarto per difettosità prodotto (qualità)', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteWorkInt', @level2type = N'COLUMN', @level2name = N'DSR';


GO
PRINT N'Creating [dbo].[QuoteWorkInt].[FC4UG].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Fixed Cost FOR Unit of Good, quota dei costi fissi per unità di prodotto finito (Copertura Costo Struttura e Linea)', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteWorkInt', @level2type = N'COLUMN', @level2name = N'FC4UG';


GO
PRINT N'Creating [dbo].[QuoteWorkInt].[VC4UG].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Variables Cost FOR Unit of Good, quota dei costi variabili per unità di prodotto finito (Costo del personale x Alx)', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteWorkInt', @level2type = N'COLUMN', @level2name = N'VC4UG';


GO
PRINT N'Creating [dbo].[QuoteWorkInt].[OH4UG].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'OH Cost FOR Unit of Good, quota dei costi Over Head per unità di prodotto finito', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteWorkInt', @level2type = N'COLUMN', @level2name = N'OH4UG';


GO
PRINT N'Creating [dbo].[QuoteWorkInt].[SC4UG].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Setup Cost FOR Unit of Good, quota dei costi di setup per unità di prodotto finito (costo cambio matrice x Alx)', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteWorkInt', @level2type = N'COLUMN', @level2name = N'SC4UG';


GO
PRINT N'Creating [dbo].[QuoteWorkInt].[WYR].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Work Yield Ratio, percentuale RESA della lavorazione (tecnico), 1 - scarto', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteWorkInt', @level2type = N'COLUMN', @level2name = N'WYR';


GO
PRINT N'Creating [dbo].[QuoteWorkInt].[MYR].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Material Yield Ratio, percentuale RESA legato alla MP (cesoia x alx), 1 - scarto', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteWorkInt', @level2type = N'COLUMN', @level2name = N'MYR';


GO
PRINT N'Creating [dbo].[QuoteWorkInt].[DYR].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Defect Yield Ratio, percentuale RESA per difettosità prodotto (qualità), 1 - scarto', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteWorkInt', @level2type = N'COLUMN', @level2name = N'DYR';


GO
PRINT N'Creating [dbo].[QuoteWorkInt].[WCR].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Work Conversion Ratio, Messa a Cento, 1 / RESA', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteWorkInt', @level2type = N'COLUMN', @level2name = N'WCR';


GO
PRINT N'Creating [dbo].[QuoteWorkInt].[MCR].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Material Conversion Ratio, Messa a Cento, 1 / RESA', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteWorkInt', @level2type = N'COLUMN', @level2name = N'MCR';


GO
PRINT N'Creating [dbo].[QuoteWorkInt].[DCR].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Defect Conversion Ratio, Messa a Cento, 1 / RESA', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteWorkInt', @level2type = N'COLUMN', @level2name = N'DCR';


GO
PRINT N'Creating [dbo].[RawMatDet].[RawMat].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'codice MP', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'RawMatDet', @level2type = N'COLUMN', @level2name = N'RawMat';


GO
PRINT N'Creating [dbo].[RawMatDet].[ProcCost].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'costo del processo di rifusione €/kg', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'RawMatDet', @level2type = N'COLUMN', @level2name = N'ProcCost';


GO
PRINT N'Creating [dbo].[RawMatDet].[ProcYield].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'resa del processo di rifusione %', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'RawMatDet', @level2type = N'COLUMN', @level2name = N'ProcYield';


GO
PRINT N'Creating [dbo].[RawMatDet].[CSR].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Cut Scrape Ratio, percentuale scarto cesoia', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'RawMatDet', @level2type = N'COLUMN', @level2name = N'CSR';


GO
PRINT N'Creating [dbo].[RawMatDet].[SSR].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Scrape Sell Ratio, percentuale di vendita dello scarto ( da 0 a 1)', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'RawMatDet', @level2type = N'COLUMN', @level2name = N'SSR';


GO
PRINT N'Creating [dbo].[RawMatDet].[SSVA].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Scrape Sell Value - ABSOLUTE, valore di vendita dello scarto ASSOLUTO', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'RawMatDet', @level2type = N'COLUMN', @level2name = N'SSVA';


GO
PRINT N'Creating [dbo].[RawMatDet].[SSVR].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Scrape Sell Value - RELATIVE come valore % del valore lega', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'RawMatDet', @level2type = N'COLUMN', @level2name = N'SSVR';


GO
PRINT N'Creating [dbo].[RawMatDet].[ExtraMatCost].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Costo extra di acquisto del materiale', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'RawMatDet', @level2type = N'COLUMN', @level2name = N'ExtraMatCost';


GO
PRINT N'Creating [dbo].[RawMatDet].[ExtraServCost].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Costo extra dei servizi sul materiale (es ultrasuoni)', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'RawMatDet', @level2type = N'COLUMN', @level2name = N'ExtraServCost';


GO
PRINT N'Creating [dbo].[TabProdSc].[ProdTeo].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'produttività teorica (kgTeorici / durata h)', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'TabProdSc', @level2type = N'COLUMN', @level2name = N'ProdTeo';


GO
PRINT N'Creating [dbo].[TabProdSc].[ScTec].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'scarto tecnico: 1 - (KgTeorici/ISNULL(KgLordi,1))', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'TabProdSc', @level2type = N'COLUMN', @level2name = N'ScTec';


GO
PRINT N'Creating [dbo].[v_selItems].[MS_DiagramPane1]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_DiagramPane1', @value = N'[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 = "ItemDet"
            Begin Extent = 
               Top = 6
               Left = 38
               Bottom = 254
               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 = 4635
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
      End
   End
   Begin CriteriaPane = 
      Begin ColumnWidths = 11
         Column = 1440
         Alias = 900
         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
', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'VIEW', @level1name = N'v_selItems';


GO
PRINT N'Creating [dbo].[v_selItems].[MS_DiagramPaneCount]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_DiagramPaneCount', @value = 1, @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'VIEW', @level1name = N'v_selItems';


GO
PRINT N'Creating [dbo].[TrascDies].[Note]...';


GO
EXECUTE sp_addextendedproperty @name = N'Note', @value = N'Tabella per Trascodifica dati in Dati DEMO', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'TrascDies';


GO
PRINT N'Creating [dbo].[TrascItem].[Note]...';


GO
EXECUTE sp_addextendedproperty @name = N'Note', @value = N'Tabella per Trascodifica dati in Dati DEMO', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'TrascItem';


GO
PRINT N'Creating [dbo].[TrascPlan].[Note]...';


GO
EXECUTE sp_addextendedproperty @name = N'Note', @value = N'Tabella per Trascodifica dati in Dati DEMO', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'TrascPlan';


GO
PRINT N'Creating [dbo].[OrdersHist].[OrdNum].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'numero ordine', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'OrdersHist', @level2type = N'COLUMN', @level2name = N'OrdNum';


GO
PRINT N'Creating [dbo].[OrdersHist].[OrdRow].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'riga ordine', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'OrdersHist', @level2type = N'COLUMN', @level2name = N'OrdRow';


GO
PRINT N'Creating [dbo].[OrdersHist].[OrdDate].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'data dell''ordine', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'OrdersHist', @level2type = N'COLUMN', @level2name = N'OrdDate';


GO
PRINT N'Creating [dbo].[OrdersHist].[CodClient].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'codice cliente', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'OrdersHist', @level2type = N'COLUMN', @level2name = N'CodClient';


GO
PRINT N'Creating [dbo].[OrdersHist].[CodItem].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'codice articolo', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'OrdersHist', @level2type = N'COLUMN', @level2name = N'CodItem';


GO
PRINT N'Creating [dbo].[OrdersHist].[RawMat].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'codice MP', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'OrdersHist', @level2type = N'COLUMN', @level2name = N'RawMat';


GO
PRINT N'Creating [dbo].[OrdersHist].[RawMatCost].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'costo della MP €/kg', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'OrdersHist', @level2type = N'COLUMN', @level2name = N'RawMatCost';


GO
PRINT N'Creating [dbo].[OrdersHist].[BatchQty].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Quantità lotto kg', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'OrdersHist', @level2type = N'COLUMN', @level2name = N'BatchQty';


GO
PRINT N'Creating [dbo].[OrdersHist].[CodInco].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Codice Incoterms', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'OrdersHist', @level2type = N'COLUMN', @level2name = N'CodInco';


GO
PRINT N'Creating [dbo].[OrdersHist].[OrdPrice].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Prezzo finale ordine', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'OrdersHist', @level2type = N'COLUMN', @level2name = N'OrdPrice';


GO
PRINT N'Creating [dbo].[OrdersHist].[QuoteType].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'tipo di preventivo: Q = quote, S = simulation', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'OrdersHist', @level2type = N'COLUMN', @level2name = N'QuoteType';


GO
PRINT N'Creating [dbo].[OrdersHist].[CodQuote].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'numero nel formato yyMMddnnnn dove nnn è incrementale giornaliero', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'OrdersHist', @level2type = N'COLUMN', @level2name = N'CodQuote';


GO
PRINT N'Creating [dbo].[QuoteFull_R].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Resa', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteFull_R';


GO
PRINT N'Creating [dbo].[QuoteFull_R].[IdxQState].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Stato offerta: 0 = D raft, 1 = C ompleted / in approvazione, 2 = A pprouved, 3 = R eleased', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteFull_R', @level2type = N'COLUMN', @level2name = N'IdxQState';


GO
PRINT N'Creating [dbo].[QuoteFull_R].[TranspZone].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Classificazione cliente (es zona, provincia...) x incrocio con tab costi trasporto', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteFull_R', @level2type = N'COLUMN', @level2name = N'TranspZone';


GO
PRINT N'Creating [dbo].[QuoteFull_R].[PriceOff].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Prezzo Offerto', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteFull_R', @level2type = N'COLUMN', @level2name = N'PriceOff';


GO
PRINT N'Creating [dbo].[QuoteFull_R].[errorScore].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'punteggio complessivo errori in procedure di calcolo', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteFull_R', @level2type = N'COLUMN', @level2name = N'errorScore';


GO
PRINT N'Creating [dbo].[QuoteSimPar].[QuoteType].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'tipo di preventivo: Q = quote, S = simulation', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteSimPar', @level2type = N'COLUMN', @level2name = N'QuoteType';


GO
PRINT N'Creating [dbo].[QuoteSimPar].[CodQuote].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'numero nel formato yyMMddnnnn dove nnn è incrementale giornaliero', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteSimPar', @level2type = N'COLUMN', @level2name = N'CodQuote';


GO
PRINT N'Creating [dbo].[ReportPrintTicket].[Ticket].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Ticket univoco per stampa', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'ReportPrintTicket', @level2type = N'COLUMN', @level2name = N'Ticket';


GO
PRINT N'Creating [dbo].[ReportPrintTicket].[Chiave].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'chiave multipla richiesta (specifica epr report)', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'ReportPrintTicket', @level2type = N'COLUMN', @level2name = N'Chiave';


GO
PRINT N'Creating [dbo].[ReportPrintTicket].[UserReq].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'user richiesta', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'ReportPrintTicket', @level2type = N'COLUMN', @level2name = N'UserReq';


GO
PRINT N'Creating [dbo].[ReportPrintTicket].[DataReq].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'data richiesta', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'ReportPrintTicket', @level2type = N'COLUMN', @level2name = N'DataReq';


GO
PRINT N'Creating [dbo].[ReportPrintTicket].[DataPrint].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'data stampa', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'ReportPrintTicket', @level2type = N'COLUMN', @level2name = N'DataPrint';


GO
PRINT N'Creating [dbo].[TrascClass01].[Note]...';


GO
EXECUTE sp_addextendedproperty @name = N'Note', @value = N'Tabella per Trascodifica dati in Dati DEMO', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'TrascClass01';


GO
PRINT N'Creating [dbo].[TrascClass02].[Note]...';


GO
EXECUTE sp_addextendedproperty @name = N'Note', @value = N'Tabella per Trascodifica dati in Dati DEMO', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'TrascClass02';


GO
PRINT N'Creating [dbo].[TrascClass03].[Note]...';


GO
EXECUTE sp_addextendedproperty @name = N'Note', @value = N'Tabella per Trascodifica dati in Dati DEMO', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'TrascClass03';


GO
PRINT N'Creating [dbo].[TrascClient].[Note]...';


GO
EXECUTE sp_addextendedproperty @name = N'Note', @value = N'Tabella per Trascodifica dati in Dati DEMO', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'TrascClient';


GO
PRINT N'Creating [dbo].[v_pivot].[MS_DiagramPaneCount]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_DiagramPaneCount', @value = 1, @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'VIEW', @level1name = N'v_pivot';


GO
PRINT N'Creating [dbo].[v_pivot].[MS_DiagramPane1]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_DiagramPane1', @value = N'[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 = 
      End
   End
   Begin SQLPane = 
   End
   Begin DataPane = 
      Begin ParameterDefaults = ""
      End
   End
   Begin CriteriaPane = 
      Begin ColumnWidths = 11
         Column = 1440
         Alias = 900
         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
', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'VIEW', @level1name = N'v_pivot';


GO
PRINT N'Creating [dbo].[v_selDateStdCost].[MS_DiagramPaneCount]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_DiagramPaneCount', @value = 1, @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'VIEW', @level1name = N'v_selDateStdCost';


GO
PRINT N'Creating [dbo].[v_selDateStdCost].[MS_DiagramPane1]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_DiagramPane1', @value = N'[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 = "QuoteFull_C"
            Begin Extent = 
               Top = 6
               Left = 38
               Bottom = 136
               Right = 213
            End
            DisplayFlags = 280
            TopColumn = 0
         End
      End
   End
   Begin SQLPane = 
   End
   Begin DataPane = 
      Begin ParameterDefaults = ""
      End
   End
   Begin CriteriaPane = 
      Begin ColumnWidths = 11
         Column = 1440
         Alias = 900
         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
', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'VIEW', @level1name = N'v_selDateStdCost';


GO
PRINT N'Creating [dbo].[v_selPackage].[MS_DiagramPaneCount]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_DiagramPaneCount', @value = 1, @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'VIEW', @level1name = N'v_selPackage';


GO
PRINT N'Creating [dbo].[v_selPackage].[MS_DiagramPane1]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_DiagramPane1', @value = N'[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 = "PackagDet"
            Begin Extent = 
               Top = 6
               Left = 38
               Bottom = 136
               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 = 11
         Column = 1440
         Alias = 900
         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
', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'VIEW', @level1name = N'v_selPackage';


GO
PRINT N'Creating [dbo].[v_selPlant].[MS_DiagramPaneCount]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_DiagramPaneCount', @value = 1, @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'VIEW', @level1name = N'v_selPlant';


GO
PRINT N'Creating [dbo].[v_selPlant].[MS_DiagramPane1]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_DiagramPane1', @value = N'[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 = "PlantsDet"
            Begin Extent = 
               Top = 6
               Left = 38
               Bottom = 119
               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 = 11
         Column = 1440
         Alias = 900
         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
', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'VIEW', @level1name = N'v_selPlant';


GO
PRINT N'Creating [dbo].[v_StdCostList].[MS_DiagramPaneCount]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_DiagramPaneCount', @value = 1, @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'VIEW', @level1name = N'v_StdCostList';


GO
PRINT N'Creating [dbo].[v_StdCostList].[MS_DiagramPane1]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_DiagramPane1', @value = N'[0E232FF0-B466-11cf-A24F-00AA00A3EFFF, 1.00]
Begin DesignProperties = 
   Begin PaneConfigurations = 
      Begin PaneConfiguration = 0
         NumPanes = 4
         Configuration = "(H (1[41] 4[20] 2[8] 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 = "QuoteFull_C"
            Begin Extent = 
               Top = 6
               Left = 38
               Bottom = 136
               Right = 213
            End
            DisplayFlags = 280
            TopColumn = 0
         End
      End
   End
   Begin SQLPane = 
   End
   Begin DataPane = 
      Begin ParameterDefaults = ""
      End
      Begin ColumnWidths = 16
         Width = 284
         Width = 2205
         Width = 2250
         Width = 1200
         Width = 915
         Width = 720
         Width = 1065
         Width = 1230
         Width = 840
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
      End
   End
   Begin CriteriaPane = 
      Begin ColumnWidths = 11
         Column = 1440
         Alias = 900
         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
', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'VIEW', @level1name = N'v_StdCostList';


GO
PRINT N'Creating [dbo].[v_listinoArticoli].[MS_DiagramPaneCount]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_DiagramPaneCount', @value = 1, @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'VIEW', @level1name = N'v_listinoArticoli';


GO
PRINT N'Creating [dbo].[v_listinoArticoli].[MS_DiagramPane1]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_DiagramPane1', @value = N'[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 = "ProductionLog"
            Begin Extent = 
               Top = 26
               Left = 424
               Bottom = 347
               Right = 594
            End
            DisplayFlags = 280
            TopColumn = 0
         End
         Begin Table = "DiesDet"
            Begin Extent = 
               Top = 77
               Left = 128
               Bottom = 247
               Right = 298
            End
            DisplayFlags = 280
            TopColumn = 0
         End
         Begin Table = "RawMatDet"
            Begin Extent = 
               Top = 138
               Left = 703
               Bottom = 360
               Right = 873
            End
            DisplayFlags = 280
            TopColumn = 0
         End
      End
   End
   Begin SQLPane = 
   End
   Begin DataPane = 
      Begin ParameterDefaults = ""
      End
      Begin ColumnWidths = 13
         Width = 284
         Width = 2055
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
      End
   End
   Begin CriteriaPane = 
      Begin ColumnWidths = 11
         Column = 1440
         Alias = 900
         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
', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'VIEW', @level1name = N'v_listinoArticoli';


GO
PRINT N'Creating [dbo].[v_MarginReportStats].[MS_DiagramPaneCount]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_DiagramPaneCount', @value = 1, @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'VIEW', @level1name = N'v_MarginReportStats';


GO
PRINT N'Creating [dbo].[v_MarginReportStats].[MS_DiagramPane1]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_DiagramPane1', @value = N'[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 = "QuoteFull_R"
            Begin Extent = 
               Top = 6
               Left = 38
               Bottom = 273
               Right = 237
            End
            DisplayFlags = 280
            TopColumn = 0
         End
      End
   End
   Begin SQLPane = 
   End
   Begin DataPane = 
      Begin ParameterDefaults = ""
      End
   End
   Begin CriteriaPane = 
      Begin ColumnWidths = 12
         Column = 1440
         Alias = 900
         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
', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'VIEW', @level1name = N'v_MarginReportStats';


GO
PRINT N'Creating [dbo].[v_MarginReportStatsNewData].[MS_DiagramPaneCount]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_DiagramPaneCount', @value = 1, @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'VIEW', @level1name = N'v_MarginReportStatsNewData';


GO
PRINT N'Creating [dbo].[v_MarginReportStatsNewData].[MS_DiagramPane1]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_DiagramPane1', @value = N'[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 = "OrdersHistRaw (ext)"
            Begin Extent = 
               Top = 6
               Left = 38
               Bottom = 298
               Right = 219
            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 = 900
         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
', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'VIEW', @level1name = N'v_MarginReportStatsNewData';


GO
PRINT N'Creating [dbo].[v_QuoteFull_Q].[MS_DiagramPane1]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_DiagramPane1', @value = N'[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 = -672
         Left = 0
      End
      Begin Tables = 
      End
   End
   Begin SQLPane = 
   End
   Begin DataPane = 
      Begin ParameterDefaults = ""
      End
      Begin ColumnWidths = 101
         Width = 284
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
        ', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'VIEW', @level1name = N'v_QuoteFull_Q';


GO
PRINT N'Creating [dbo].[v_QuoteFull_Q].[MS_DiagramPaneCount]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_DiagramPaneCount', @value = 2, @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'VIEW', @level1name = N'v_QuoteFull_Q';


GO
PRINT N'Creating [dbo].[v_QuoteFull_Q].[MS_DiagramPane2]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_DiagramPane2', @value = N' Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
      End
   End
   Begin CriteriaPane = 
      Begin ColumnWidths = 11
         Column = 1440
         Alias = 900
         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
', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'VIEW', @level1name = N'v_QuoteFull_Q';


GO
PRINT N'Creating [dbo].[v_selListVal].[MS_DiagramPaneCount]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_DiagramPaneCount', @value = 1, @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'VIEW', @level1name = N'v_selListVal';


GO
PRINT N'Creating [dbo].[v_selListVal].[MS_DiagramPane1]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_DiagramPane1', @value = N'[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 = "ListValues"
            Begin Extent = 
               Top = 6
               Left = 38
               Bottom = 136
               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 = 11
         Column = 1440
         Alias = 900
         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
', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'VIEW', @level1name = N'v_selListVal';


GO
PRINT N'Creating [dbo].[v_MarginReport].[MS_DiagramPaneCount]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_DiagramPaneCount', @value = 2, @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'VIEW', @level1name = N'v_MarginReport';


GO
PRINT N'Creating [dbo].[v_MarginReport].[MS_DiagramPane2]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_DiagramPane2', @value = N'
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
      End
   End
   Begin CriteriaPane = 
      Begin ColumnWidths = 11
         Column = 12180
         Alias = 1725
         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
', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'VIEW', @level1name = N'v_MarginReport';


GO
PRINT N'Creating [dbo].[v_MarginReport].[MS_DiagramPane1]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_DiagramPane1', @value = N'[0E232FF0-B466-11cf-A24F-00AA00A3EFFF, 1.00]
Begin DesignProperties = 
   Begin PaneConfigurations = 
      Begin PaneConfiguration = 0
         NumPanes = 4
         Configuration = "(H (1[25] 4[31] 2[14] 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 = "QuoteFull_R"
            Begin Extent = 
               Top = 5
               Left = 30
               Bottom = 226
               Right = 213
            End
            DisplayFlags = 280
            TopColumn = 69
         End
      End
   End
   Begin SQLPane = 
   End
   Begin DataPane = 
      Begin ParameterDefaults = ""
      End
      Begin ColumnWidths = 109
         Width = 284
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 2445
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'VIEW', @level1name = N'v_MarginReport';


GO
PRINT N'Creating [dbo].[QuoteFull_S].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Simulation', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteFull_S';


GO
PRINT N'Creating [dbo].[QuoteFull_S].[DiesPrice_sim].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'costo matrice per SIMULAZIONE', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteFull_S', @level2type = N'COLUMN', @level2name = N'DiesPrice_sim';


GO
PRINT N'Creating [dbo].[QuoteFull_S].[SamplePrice].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'costo prove', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteFull_S', @level2type = N'COLUMN', @level2name = N'SamplePrice';


GO
PRINT N'Creating [dbo].[QuoteFull_S].[DiesFullCost].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'costo prove', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteFull_S', @level2type = N'COLUMN', @level2name = N'DiesFullCost';


GO
PRINT N'Creating [dbo].[QuoteFull_S].[DiesTecLife].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Durata tecnica stimata', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteFull_S', @level2type = N'COLUMN', @level2name = N'DiesTecLife';


GO
PRINT N'Creating [dbo].[QuoteFull_S].[DiesCommLife].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Durata commerciale in kg', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteFull_S', @level2type = N'COLUMN', @level2name = N'DiesCommLife';


GO
PRINT N'Creating [dbo].[QuoteFull_S].[MonthSalesPrev].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Durata commerciale in mesi prevista', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteFull_S', @level2type = N'COLUMN', @level2name = N'MonthSalesPrev';


GO
PRINT N'Creating [dbo].[QuoteFull_S].[SalesPrevCost].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'costi per durata commerciale', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteFull_S', @level2type = N'COLUMN', @level2name = N'SalesPrevCost';


GO
PRINT N'Creating [dbo].[QuoteFull_S].[DiesFinCost].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'oneri finanziari anticipo matrice', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteFull_S', @level2type = N'COLUMN', @level2name = N'DiesFinCost';


GO
PRINT N'Creating [dbo].[QuoteFull_S].[ClientQuoteReven].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Ricavo quota cliente', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteFull_S', @level2type = N'COLUMN', @level2name = N'ClientQuoteReven';


GO
PRINT N'Creating [dbo].[QuoteFull_S].[ExtraDiscountDies].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Ricavo quota cliente', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteFull_S', @level2type = N'COLUMN', @level2name = N'ExtraDiscountDies';


GO
PRINT N'Creating [dbo].[QuoteFull_S].[WSR01_sim].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'scarto tecnico SIMULAZIONE', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteFull_S', @level2type = N'COLUMN', @level2name = N'WSR01_sim';


GO
PRINT N'Creating [dbo].[QuoteFull_S].[WSR01].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'scarto tecnico medio AMIL', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteFull_S', @level2type = N'COLUMN', @level2name = N'WSR01';


GO
PRINT N'Creating [dbo].[QuoteFull_S].[MSR01_sim].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'scarto cesoia SIMULAZIONE', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteFull_S', @level2type = N'COLUMN', @level2name = N'MSR01_sim';


GO
PRINT N'Creating [dbo].[QuoteFull_S].[MSR01].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'scarto cesoia medio AMIL', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteFull_S', @level2type = N'COLUMN', @level2name = N'MSR01';


GO
PRINT N'Creating [dbo].[QuoteFull_S].[NetProd01_sim].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'produttività teorica SIMULAZIONE', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteFull_S', @level2type = N'COLUMN', @level2name = N'NetProd01_sim';


GO
PRINT N'Creating [dbo].[QuoteFull_S].[NetProd04_sim].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'produttività teorica SIMULAZIONE', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteFull_S', @level2type = N'COLUMN', @level2name = N'NetProd04_sim';


GO
PRINT N'Creating [dbo].[QuoteFull_S].[NetProd01].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'produttività teorica medio AMIL', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteFull_S', @level2type = N'COLUMN', @level2name = N'NetProd01';


GO
PRINT N'Creating [dbo].[QuoteFull_S].[DSR_sim].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'scarto medio SIMULAZIONE', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteFull_S', @level2type = N'COLUMN', @level2name = N'DSR_sim';


GO
PRINT N'Creating [dbo].[QuoteFull_S].[DSR].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'scarto medio AMI', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'QuoteFull_S', @level2type = N'COLUMN', @level2name = N'DSR';


GO
PRINT N'Creating [tmp].[ProductionLogRaw_KO].[okPr].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'validazione riga x calcolo produttività', @level0type = N'SCHEMA', @level0name = N'tmp', @level1type = N'TABLE', @level1name = N'ProductionLogRaw_KO', @level2type = N'COLUMN', @level2name = N'okPr';


GO
PRINT N'Creating [tmp].[ProductionLogRaw_KO].[okQM].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'validazione riga x calcolo quota MAN', @level0type = N'SCHEMA', @level0name = N'tmp', @level1type = N'TABLE', @level1name = N'ProductionLogRaw_KO', @level2type = N'COLUMN', @level2name = N'okQM';


GO
PRINT N'Creating [tmp].[ProductionLogRaw_KO].[okSc].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'validazione riga x calcolo scarti', @level0type = N'SCHEMA', @level0name = N'tmp', @level1type = N'TABLE', @level1name = N'ProductionLogRaw_KO', @level2type = N'COLUMN', @level2name = N'okSc';


GO
PRINT N'Creating [tmp].[ProductionLogRaw_KO].[okDi].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'validazione riga x calcolo difettosità', @level0type = N'SCHEMA', @level0name = N'tmp', @level1type = N'TABLE', @level1name = N'ProductionLogRaw_KO', @level2type = N'COLUMN', @level2name = N'okDi';


GO
PRINT N'Creating [tmp].[ClientsRaw].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'', @level0type = N'SCHEMA', @level0name = N'tmp', @level1type = N'TABLE', @level1name = N'ClientsRaw';


GO
PRINT N'Creating [tmp].[ClientsRaw].[CodClient].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'codice cliente', @level0type = N'SCHEMA', @level0name = N'tmp', @level1type = N'TABLE', @level1name = N'ClientsRaw', @level2type = N'COLUMN', @level2name = N'CodClient';


GO
PRINT N'Creating [tmp].[ClientsRaw].[ClientName].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Ragione Sociale', @level0type = N'SCHEMA', @level0name = N'tmp', @level1type = N'TABLE', @level1name = N'ClientsRaw', @level2type = N'COLUMN', @level2name = N'ClientName';


GO
PRINT N'Creating [tmp].[ClientsRaw].[CodAg].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'codice agente...', @level0type = N'SCHEMA', @level0name = N'tmp', @level1type = N'TABLE', @level1name = N'ClientsRaw', @level2type = N'COLUMN', @level2name = N'CodAg';


GO
PRINT N'Creating [tmp].[ClientsRaw].[ZipCode].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'cap', @level0type = N'SCHEMA', @level0name = N'tmp', @level1type = N'TABLE', @level1name = N'ClientsRaw', @level2type = N'COLUMN', @level2name = N'ZipCode';


GO
PRINT N'Creating [tmp].[ClientsRaw].[City].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'città', @level0type = N'SCHEMA', @level0name = N'tmp', @level1type = N'TABLE', @level1name = N'ClientsRaw', @level2type = N'COLUMN', @level2name = N'City';


GO
PRINT N'Creating [tmp].[ClientsRaw].[State].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'stato/provincia', @level0type = N'SCHEMA', @level0name = N'tmp', @level1type = N'TABLE', @level1name = N'ClientsRaw', @level2type = N'COLUMN', @level2name = N'State';


GO
PRINT N'Creating [tmp].[ClientsRaw].[Nation].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'nazione', @level0type = N'SCHEMA', @level0name = N'tmp', @level1type = N'TABLE', @level1name = N'ClientsRaw', @level2type = N'COLUMN', @level2name = N'Nation';


GO
PRINT N'Creating [tmp].[ClientsRaw].[TranspZone].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Classificazione cliente (es zona, provincia...) x incrocio con tab costi trasporto', @level0type = N'SCHEMA', @level0name = N'tmp', @level1type = N'TABLE', @level1name = N'ClientsRaw', @level2type = N'COLUMN', @level2name = N'TranspZone';


GO
PRINT N'Creating [tmp].[ItemsRaw].[CodItem].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'codice articolo', @level0type = N'SCHEMA', @level0name = N'tmp', @level1type = N'TABLE', @level1name = N'ItemsRaw', @level2type = N'COLUMN', @level2name = N'CodItem';


GO
PRINT N'Creating [tmp].[ItemsRaw].[CodItemGroup].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'calsse raggruppamento (es complessità disegno)', @level0type = N'SCHEMA', @level0name = N'tmp', @level1type = N'TABLE', @level1name = N'ItemsRaw', @level2type = N'COLUMN', @level2name = N'CodItemGroup';


GO
PRINT N'Creating [tmp].[ItemsRaw].[Class01].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'', @level0type = N'SCHEMA', @level0name = N'tmp', @level1type = N'TABLE', @level1name = N'ItemsRaw', @level2type = N'COLUMN', @level2name = N'Class01';


GO
PRINT N'Creating [tmp].[ProductionLogRaw].[okPr].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'validazione riga x calcolo produttività', @level0type = N'SCHEMA', @level0name = N'tmp', @level1type = N'TABLE', @level1name = N'ProductionLogRaw', @level2type = N'COLUMN', @level2name = N'okPr';


GO
PRINT N'Creating [tmp].[ProductionLogRaw].[okQM].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'validazione riga x calcolo quota MAN', @level0type = N'SCHEMA', @level0name = N'tmp', @level1type = N'TABLE', @level1name = N'ProductionLogRaw', @level2type = N'COLUMN', @level2name = N'okQM';


GO
PRINT N'Creating [tmp].[ProductionLogRaw].[okSc].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'validazione riga x calcolo scarti', @level0type = N'SCHEMA', @level0name = N'tmp', @level1type = N'TABLE', @level1name = N'ProductionLogRaw', @level2type = N'COLUMN', @level2name = N'okSc';


GO
PRINT N'Creating [tmp].[ProductionLogRaw].[okDi].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'validazione riga x calcolo difettosità', @level0type = N'SCHEMA', @level0name = N'tmp', @level1type = N'TABLE', @level1name = N'ProductionLogRaw', @level2type = N'COLUMN', @level2name = N'okDi';


GO
PRINT N'Creating [tmp].[PackagRaw].[RMCost].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Raw Material Cost - costo dei materiali', @level0type = N'SCHEMA', @level0name = N'tmp', @level1type = N'TABLE', @level1name = N'PackagRaw', @level2type = N'COLUMN', @level2name = N'RMCost';


GO
PRINT N'Creating [tmp].[PackagRaw].[RMWeight].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'kg peso medio', @level0type = N'SCHEMA', @level0name = N'tmp', @level1type = N'TABLE', @level1name = N'PackagRaw', @level2type = N'COLUMN', @level2name = N'RMWeight';


GO
PRINT N'Creating [tmp].[PackagRaw].[Tare].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'kg tara standard', @level0type = N'SCHEMA', @level0name = N'tmp', @level1type = N'TABLE', @level1name = N'PackagRaw', @level2type = N'COLUMN', @level2name = N'Tare';


GO
PRINT N'Creating [tmp].[PackagRaw].[FullWeight].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'peso medio del pacco (compelssivo)', @level0type = N'SCHEMA', @level0name = N'tmp', @level1type = N'TABLE', @level1name = N'PackagRaw', @level2type = N'COLUMN', @level2name = N'FullWeight';


GO
PRINT N'Creating [tmp].[OrdersHistRaw].[Note]...';


GO
EXECUTE sp_addextendedproperty @name = N'Note', @value = N'Import storico ordini per Quote_C', @level0type = N'SCHEMA', @level0name = N'tmp', @level1type = N'TABLE', @level1name = N'OrdersHistRaw';


GO
PRINT N'Creating [tmp].[OrdersHistRaw].[OrdPrice].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Prezzo finale ordine', @level0type = N'SCHEMA', @level0name = N'tmp', @level1type = N'TABLE', @level1name = N'OrdersHistRaw', @level2type = N'COLUMN', @level2name = N'OrdPrice';


GO
PRINT N'Creating [ext].[ClientsRaw].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'', @level0type = N'SCHEMA', @level0name = N'ext', @level1type = N'TABLE', @level1name = N'ClientsRaw';


GO
PRINT N'Creating [ext].[ClientsRaw].[CodClient].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'codice cliente', @level0type = N'SCHEMA', @level0name = N'ext', @level1type = N'TABLE', @level1name = N'ClientsRaw', @level2type = N'COLUMN', @level2name = N'CodClient';


GO
PRINT N'Creating [ext].[ClientsRaw].[ClientName].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Ragione Sociale', @level0type = N'SCHEMA', @level0name = N'ext', @level1type = N'TABLE', @level1name = N'ClientsRaw', @level2type = N'COLUMN', @level2name = N'ClientName';


GO
PRINT N'Creating [ext].[ClientsRaw].[CodAg].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'codice agente...', @level0type = N'SCHEMA', @level0name = N'ext', @level1type = N'TABLE', @level1name = N'ClientsRaw', @level2type = N'COLUMN', @level2name = N'CodAg';


GO
PRINT N'Creating [ext].[ClientsRaw].[ZipCode].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'cap', @level0type = N'SCHEMA', @level0name = N'ext', @level1type = N'TABLE', @level1name = N'ClientsRaw', @level2type = N'COLUMN', @level2name = N'ZipCode';


GO
PRINT N'Creating [ext].[ClientsRaw].[City].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'città', @level0type = N'SCHEMA', @level0name = N'ext', @level1type = N'TABLE', @level1name = N'ClientsRaw', @level2type = N'COLUMN', @level2name = N'City';


GO
PRINT N'Creating [ext].[ClientsRaw].[State].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'stato/provincia', @level0type = N'SCHEMA', @level0name = N'ext', @level1type = N'TABLE', @level1name = N'ClientsRaw', @level2type = N'COLUMN', @level2name = N'State';


GO
PRINT N'Creating [ext].[ClientsRaw].[Nation].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'nazione', @level0type = N'SCHEMA', @level0name = N'ext', @level1type = N'TABLE', @level1name = N'ClientsRaw', @level2type = N'COLUMN', @level2name = N'Nation';


GO
PRINT N'Creating [ext].[ClientsRaw].[TranspZone].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Classificazione cliente (es zona, provincia...) x incrocio con tab costi trasporto', @level0type = N'SCHEMA', @level0name = N'ext', @level1type = N'TABLE', @level1name = N'ClientsRaw', @level2type = N'COLUMN', @level2name = N'TranspZone';


GO
PRINT N'Creating [ext].[ProductionLogRaw].[EventStart].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'inizio evento - formato INT 16 cifre yyyyMMddHHmmssnn dove nn = centesimi di sec oppure 00', @level0type = N'SCHEMA', @level0name = N'ext', @level1type = N'TABLE', @level1name = N'ProductionLogRaw', @level2type = N'COLUMN', @level2name = N'EventStart';


GO
PRINT N'Creating [ext].[ProductionLogRaw].[EventEnd].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'fine evento - formato INT 16 cifre yyyyMMddHHmmssnn dove nn = centesimi di sec oppure 00', @level0type = N'SCHEMA', @level0name = N'ext', @level1type = N'TABLE', @level1name = N'ProductionLogRaw', @level2type = N'COLUMN', @level2name = N'EventEnd';


GO
PRINT N'Creating [ext].[ProductionLogRaw].[CodPlant].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'codice impianto', @level0type = N'SCHEMA', @level0name = N'ext', @level1type = N'TABLE', @level1name = N'ProductionLogRaw', @level2type = N'COLUMN', @level2name = N'CodPlant';


GO
PRINT N'Creating [ext].[ProductionLogRaw].[ProcessNum].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'codice fase, da qui si crea anagrafica fasi distinct', @level0type = N'SCHEMA', @level0name = N'ext', @level1type = N'TABLE', @level1name = N'ProductionLogRaw', @level2type = N'COLUMN', @level2name = N'ProcessNum';


GO
PRINT N'Creating [ext].[ProductionLogRaw].[CodDies].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'codice matrice', @level0type = N'SCHEMA', @level0name = N'ext', @level1type = N'TABLE', @level1name = N'ProductionLogRaw', @level2type = N'COLUMN', @level2name = N'CodDies';


GO
PRINT N'Creating [ext].[ProductionLogRaw].[CodClient].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'codice cliente', @level0type = N'SCHEMA', @level0name = N'ext', @level1type = N'TABLE', @level1name = N'ProductionLogRaw', @level2type = N'COLUMN', @level2name = N'CodClient';


GO
PRINT N'Creating [ext].[ProductionLogRaw].[OrderNum].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'rif codice ordine', @level0type = N'SCHEMA', @level0name = N'ext', @level1type = N'TABLE', @level1name = N'ProductionLogRaw', @level2type = N'COLUMN', @level2name = N'OrderNum';


GO
PRINT N'Creating [ext].[ProductionLogRaw].[BatchNum].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'codice lotto', @level0type = N'SCHEMA', @level0name = N'ext', @level1type = N'TABLE', @level1name = N'ProductionLogRaw', @level2type = N'COLUMN', @level2name = N'BatchNum';


GO
PRINT N'Creating [ext].[ProductionLogRaw].[ProcessType].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'codice del TIPO di fase, x raggruppamento funzionale', @level0type = N'SCHEMA', @level0name = N'ext', @level1type = N'TABLE', @level1name = N'ProductionLogRaw', @level2type = N'COLUMN', @level2name = N'ProcessType';


GO
PRINT N'Creating [ext].[ProductionLogRaw].[EventType].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'tipo evento: produzione, prova, guasto, setup...', @level0type = N'SCHEMA', @level0name = N'ext', @level1type = N'TABLE', @level1name = N'ProductionLogRaw', @level2type = N'COLUMN', @level2name = N'EventType';


GO
PRINT N'Creating [ext].[ProductionLogRaw].[RawMat].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'codice MP', @level0type = N'SCHEMA', @level0name = N'ext', @level1type = N'TABLE', @level1name = N'ProductionLogRaw', @level2type = N'COLUMN', @level2name = N'RawMat';


GO
PRINT N'Creating [ext].[ProductionLogRaw].[CodPackag].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'codice imballo', @level0type = N'SCHEMA', @level0name = N'ext', @level1type = N'TABLE', @level1name = N'ProductionLogRaw', @level2type = N'COLUMN', @level2name = N'CodPackag';


GO
PRINT N'Creating [ext].[ProductionLogRaw].[QtyIN].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'kg materiale in ingresso', @level0type = N'SCHEMA', @level0name = N'ext', @level1type = N'TABLE', @level1name = N'ProductionLogRaw', @level2type = N'COLUMN', @level2name = N'QtyIN';


GO
PRINT N'Creating [ext].[ProductionLogRaw].[QtyOUT].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'kg materiale BUONO prodotto in OUTput', @level0type = N'SCHEMA', @level0name = N'ext', @level1type = N'TABLE', @level1name = N'ProductionLogRaw', @level2type = N'COLUMN', @level2name = N'QtyOUT';


GO
PRINT N'Creating [ext].[ProductionLogRaw].[QtyEXT].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'kg materiale extra che fa parte dell''OUT, es imballi/tara', @level0type = N'SCHEMA', @level0name = N'ext', @level1type = N'TABLE', @level1name = N'ProductionLogRaw', @level2type = N'COLUMN', @level2name = N'QtyEXT';


GO
PRINT N'Creating [ext].[ProductionLogRaw].[NumIN].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'qta materiale in ingresso', @level0type = N'SCHEMA', @level0name = N'ext', @level1type = N'TABLE', @level1name = N'ProductionLogRaw', @level2type = N'COLUMN', @level2name = N'NumIN';


GO
PRINT N'Creating [ext].[ProductionLogRaw].[NumOUT].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'qta materiale BUONO prodotto in OUTput', @level0type = N'SCHEMA', @level0name = N'ext', @level1type = N'TABLE', @level1name = N'ProductionLogRaw', @level2type = N'COLUMN', @level2name = N'NumOUT';


GO
PRINT N'Creating [ext].[ProductionLogRaw].[QuotaPlant].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'indicazione della quota macchina per produrre quanto registrato', @level0type = N'SCHEMA', @level0name = N'ext', @level1type = N'TABLE', @level1name = N'ProductionLogRaw', @level2type = N'COLUMN', @level2name = N'QuotaPlant';


GO
PRINT N'Creating [ext].[ProductionLogRaw].[QuotaMan].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'indicazione della quota uomo per produrre quanto registrato', @level0type = N'SCHEMA', @level0name = N'ext', @level1type = N'TABLE', @level1name = N'ProductionLogRaw', @level2type = N'COLUMN', @level2name = N'QuotaMan';


GO
PRINT N'Creating [ext].[ProductionLogRaw].[Tags].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'categorie LIBERE, separatore #', @level0type = N'SCHEMA', @level0name = N'ext', @level1type = N'TABLE', @level1name = N'ProductionLogRaw', @level2type = N'COLUMN', @level2name = N'Tags';


GO
PRINT N'Creating [ext].[ProductionLogRaw].[okPr].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'validazione riga x calcolo produttività', @level0type = N'SCHEMA', @level0name = N'ext', @level1type = N'TABLE', @level1name = N'ProductionLogRaw', @level2type = N'COLUMN', @level2name = N'okPr';


GO
PRINT N'Creating [ext].[ProductionLogRaw].[okQM].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'validazione riga x calcolo quota MAN', @level0type = N'SCHEMA', @level0name = N'ext', @level1type = N'TABLE', @level1name = N'ProductionLogRaw', @level2type = N'COLUMN', @level2name = N'okQM';


GO
PRINT N'Creating [ext].[ProductionLogRaw].[okSc].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'validazione riga x calcolo scarti', @level0type = N'SCHEMA', @level0name = N'ext', @level1type = N'TABLE', @level1name = N'ProductionLogRaw', @level2type = N'COLUMN', @level2name = N'okSc';


GO
PRINT N'Creating [ext].[ProductionLogRaw].[okDi].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'validazione riga x calcolo difettosità', @level0type = N'SCHEMA', @level0name = N'ext', @level1type = N'TABLE', @level1name = N'ProductionLogRaw', @level2type = N'COLUMN', @level2name = N'okDi';


GO
PRINT N'Creating [ext].[ProductionLogRaw_KO].[okPr].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'validazione riga x calcolo produttività', @level0type = N'SCHEMA', @level0name = N'ext', @level1type = N'TABLE', @level1name = N'ProductionLogRaw_KO', @level2type = N'COLUMN', @level2name = N'okPr';


GO
PRINT N'Creating [ext].[ProductionLogRaw_KO].[okQM].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'validazione riga x calcolo quota MAN', @level0type = N'SCHEMA', @level0name = N'ext', @level1type = N'TABLE', @level1name = N'ProductionLogRaw_KO', @level2type = N'COLUMN', @level2name = N'okQM';


GO
PRINT N'Creating [ext].[ProductionLogRaw_KO].[okSc].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'validazione riga x calcolo scarti', @level0type = N'SCHEMA', @level0name = N'ext', @level1type = N'TABLE', @level1name = N'ProductionLogRaw_KO', @level2type = N'COLUMN', @level2name = N'okSc';


GO
PRINT N'Creating [ext].[ProductionLogRaw_KO].[okDi].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'validazione riga x calcolo difettosità', @level0type = N'SCHEMA', @level0name = N'ext', @level1type = N'TABLE', @level1name = N'ProductionLogRaw_KO', @level2type = N'COLUMN', @level2name = N'okDi';


GO
PRINT N'Creating [ext].[ItemsRaw].[CodItem].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'codice articolo', @level0type = N'SCHEMA', @level0name = N'ext', @level1type = N'TABLE', @level1name = N'ItemsRaw', @level2type = N'COLUMN', @level2name = N'CodItem';


GO
PRINT N'Creating [ext].[ItemsRaw].[CodItemGroup].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'calsse raggruppamento (es complessità disegno)', @level0type = N'SCHEMA', @level0name = N'ext', @level1type = N'TABLE', @level1name = N'ItemsRaw', @level2type = N'COLUMN', @level2name = N'CodItemGroup';


GO
PRINT N'Creating [ext].[ItemsRaw].[Class01].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'', @level0type = N'SCHEMA', @level0name = N'ext', @level1type = N'TABLE', @level1name = N'ItemsRaw', @level2type = N'COLUMN', @level2name = N'Class01';


GO
PRINT N'Creating [ext].[PackagRaw].[RMCost].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Raw Material Cost - costo dei materiali', @level0type = N'SCHEMA', @level0name = N'ext', @level1type = N'TABLE', @level1name = N'PackagRaw', @level2type = N'COLUMN', @level2name = N'RMCost';


GO
PRINT N'Creating [ext].[PackagRaw].[RMWeight].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'kg peso medio', @level0type = N'SCHEMA', @level0name = N'ext', @level1type = N'TABLE', @level1name = N'PackagRaw', @level2type = N'COLUMN', @level2name = N'RMWeight';


GO
PRINT N'Creating [ext].[PackagRaw].[Tare].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'kg tara standard', @level0type = N'SCHEMA', @level0name = N'ext', @level1type = N'TABLE', @level1name = N'PackagRaw', @level2type = N'COLUMN', @level2name = N'Tare';


GO
PRINT N'Creating [ext].[PackagRaw].[FullWeight].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'peso medio del pacco (compelssivo)', @level0type = N'SCHEMA', @level0name = N'ext', @level1type = N'TABLE', @level1name = N'PackagRaw', @level2type = N'COLUMN', @level2name = N'FullWeight';


GO
PRINT N'Creating [ext].[RcdItem].[CodItem].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'codice articolo', @level0type = N'SCHEMA', @level0name = N'ext', @level1type = N'TABLE', @level1name = N'RcdItem', @level2type = N'COLUMN', @level2name = N'CodItem';


GO
PRINT N'Creating [ext].[RcdItem].[CodItemRcd].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'codice articolo', @level0type = N'SCHEMA', @level0name = N'ext', @level1type = N'TABLE', @level1name = N'RcdItem', @level2type = N'COLUMN', @level2name = N'CodItemRcd';


GO
PRINT N'Creating [ext].[RcdClient].[CodClient].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'codice cliente', @level0type = N'SCHEMA', @level0name = N'ext', @level1type = N'TABLE', @level1name = N'RcdClient', @level2type = N'COLUMN', @level2name = N'CodClient';


GO
PRINT N'Creating [ext].[RcdClient].[CodClientRcd].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'codice cliente', @level0type = N'SCHEMA', @level0name = N'ext', @level1type = N'TABLE', @level1name = N'RcdClient', @level2type = N'COLUMN', @level2name = N'CodClientRcd';


GO
PRINT N'Creating [ext].[RcdClient].[CodAgRcd].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'codice agente...', @level0type = N'SCHEMA', @level0name = N'ext', @level1type = N'TABLE', @level1name = N'RcdClient', @level2type = N'COLUMN', @level2name = N'CodAgRcd';


GO
PRINT N'Creating [ext].[RcdClient].[ClientNameRcd].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Ragione Sociale', @level0type = N'SCHEMA', @level0name = N'ext', @level1type = N'TABLE', @level1name = N'RcdClient', @level2type = N'COLUMN', @level2name = N'ClientNameRcd';


GO
PRINT N'Creating [ext].[RcdClass01].[CodClass01].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'codice cliente', @level0type = N'SCHEMA', @level0name = N'ext', @level1type = N'TABLE', @level1name = N'RcdClass01', @level2type = N'COLUMN', @level2name = N'CodClass01';


GO
PRINT N'Creating [ext].[RcdClass01].[CodClass01Rcd].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'codice cliente', @level0type = N'SCHEMA', @level0name = N'ext', @level1type = N'TABLE', @level1name = N'RcdClass01', @level2type = N'COLUMN', @level2name = N'CodClass01Rcd';


GO
PRINT N'Creating [ext].[v_MarginReportRcd].[MS_DiagramPaneCount]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_DiagramPaneCount', @value = 2, @level0type = N'SCHEMA', @level0name = N'ext', @level1type = N'VIEW', @level1name = N'v_MarginReportRcd';


GO
PRINT N'Creating [ext].[v_MarginReportRcd].[MS_DiagramPane2]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_DiagramPane2', @value = N'= 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
      End
   End
   Begin CriteriaPane = 
      Begin ColumnWidths = 11
         Column = 1440
         Alias = 900
         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
', @level0type = N'SCHEMA', @level0name = N'ext', @level1type = N'VIEW', @level1name = N'v_MarginReportRcd';


GO
PRINT N'Creating [ext].[v_MarginReportRcd].[MS_DiagramPane1]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_DiagramPane1', @value = N'[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 = "v_MarginReport"
            Begin Extent = 
               Top = 36
               Left = 385
               Bottom = 332
               Right = 566
            End
            DisplayFlags = 280
            TopColumn = 0
         End
         Begin Table = "RcdItem (ext)"
            Begin Extent = 
               Top = 58
               Left = 639
               Bottom = 188
               Right = 809
            End
            DisplayFlags = 280
            TopColumn = 0
         End
         Begin Table = "RcdClient (ext)"
            Begin Extent = 
               Top = 52
               Left = 120
               Bottom = 164
               Right = 290
            End
            DisplayFlags = 280
            TopColumn = 0
         End
         Begin Table = "RcdPlants (ext)"
            Begin Extent = 
               Top = 195
               Left = 132
               Bottom = 291
               Right = 302
            End
            DisplayFlags = 280
            TopColumn = 0
         End
      End
   End
   Begin SQLPane = 
   End
   Begin DataPane = 
      Begin ParameterDefaults = ""
      End
      Begin ColumnWidths = 76
         Width = 284
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 3450
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 3960
         Width ', @level0type = N'SCHEMA', @level0name = N'ext', @level1type = N'VIEW', @level1name = N'v_MarginReportRcd';


GO
PRINT N'Creating [ext].[v_ItemDetRcd].[MS_DiagramPaneCount]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_DiagramPaneCount', @value = 2, @level0type = N'SCHEMA', @level0name = N'ext', @level1type = N'VIEW', @level1name = N'v_ItemDetRcd';


GO
PRINT N'Creating [ext].[v_ItemDetRcd].[MS_DiagramPane2]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_DiagramPane2', @value = N'    SortOrder = 1410
         GroupBy = 1350
         Filter = 1350
         Or = 1350
         Or = 1350
         Or = 1350
      End
   End
End
', @level0type = N'SCHEMA', @level0name = N'ext', @level1type = N'VIEW', @level1name = N'v_ItemDetRcd';


GO
PRINT N'Creating [ext].[v_ItemDetRcd].[MS_DiagramPane1]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_DiagramPane1', @value = N'[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 = "ItemDet"
            Begin Extent = 
               Top = 34
               Left = 516
               Bottom = 272
               Right = 686
            End
            DisplayFlags = 280
            TopColumn = 0
         End
         Begin Table = "RcdItem (ext)"
            Begin Extent = 
               Top = 6
               Left = 246
               Bottom = 178
               Right = 416
            End
            DisplayFlags = 280
            TopColumn = 0
         End
         Begin Table = "RcdClass01 (ext)"
            Begin Extent = 
               Top = 64
               Left = 836
               Bottom = 160
               Right = 1006
            End
            DisplayFlags = 280
            TopColumn = 0
         End
         Begin Table = "RcdClass02 (ext)"
            Begin Extent = 
               Top = 185
               Left = 840
               Bottom = 281
               Right = 1010
            End
            DisplayFlags = 280
            TopColumn = 0
         End
      End
   End
   Begin SQLPane = 
   End
   Begin DataPane = 
      Begin ParameterDefaults = ""
      End
      Begin ColumnWidths = 14
         Width = 284
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
      End
   End
   Begin CriteriaPane = 
      Begin ColumnWidths = 11
         Column = 1440
         Alias = 900
         Table = 1605
         Output = 720
         Append = 1400
         NewValue = 1170
         SortType = 1350
     ', @level0type = N'SCHEMA', @level0name = N'ext', @level1type = N'VIEW', @level1name = N'v_ItemDetRcd';


GO
PRINT N'Creating [ext].[v_ClientDetRcd].[MS_DiagramPaneCount]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_DiagramPaneCount', @value = 1, @level0type = N'SCHEMA', @level0name = N'ext', @level1type = N'VIEW', @level1name = N'v_ClientDetRcd';


GO
PRINT N'Creating [ext].[v_ClientDetRcd].[MS_DiagramPane1]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_DiagramPane1', @value = N'[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 = "ClientDet"
            Begin Extent = 
               Top = 6
               Left = 38
               Bottom = 136
               Right = 208
            End
            DisplayFlags = 280
            TopColumn = 0
         End
         Begin Table = "RcdClient (ext)"
            Begin Extent = 
               Top = 6
               Left = 246
               Bottom = 153
               Right = 416
            End
            DisplayFlags = 280
            TopColumn = 0
         End
      End
   End
   Begin SQLPane = 
   End
   Begin DataPane = 
      Begin ParameterDefaults = ""
      End
      Begin ColumnWidths = 10
         Width = 284
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
      End
   End
   Begin CriteriaPane = 
      Begin ColumnWidths = 11
         Column = 1440
         Alias = 900
         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
', @level0type = N'SCHEMA', @level0name = N'ext', @level1type = N'VIEW', @level1name = N'v_ClientDetRcd';


GO
PRINT N'Creating [ext].[RcdPlants].[CodPlant].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'codice impianto', @level0type = N'SCHEMA', @level0name = N'ext', @level1type = N'TABLE', @level1name = N'RcdPlants', @level2type = N'COLUMN', @level2name = N'CodPlant';


GO
PRINT N'Creating [ext].[RcdPlants].[CodPlantRcd].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'codice impianto', @level0type = N'SCHEMA', @level0name = N'ext', @level1type = N'TABLE', @level1name = N'RcdPlants', @level2type = N'COLUMN', @level2name = N'CodPlantRcd';


GO
DECLARE @VarDecimalSupported AS BIT;

SELECT @VarDecimalSupported = 0;

IF ((ServerProperty(N'EngineEdition') = 3)
    AND (((@@microsoftversion / power(2, 24) = 9)
          AND (@@microsoftversion & 0xffff >= 3024))
         OR ((@@microsoftversion / power(2, 24) = 10)
             AND (@@microsoftversion & 0xffff >= 1600))))
    SELECT @VarDecimalSupported = 1;

IF (@VarDecimalSupported > 0)
    BEGIN
        EXECUTE sp_db_vardecimal_storage_format N'$(DatabaseName)', 'ON';
    END


GO
ALTER DATABASE [$(DatabaseName)]
    SET MULTI_USER 
    WITH ROLLBACK IMMEDIATE;


GO
PRINT N'Update complete.';


GO
