﻿/*
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;
    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 [voc]...';


GO
CREATE SCHEMA [voc]
    AUTHORIZATION [dbo];


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


GO
CREATE SCHEMA [ext]
    AUTHORIZATION [dbo];


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


GO
CREATE SCHEMA [tmp]
    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].[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 ([NumP] ASC, [QuoteType] ASC, [CodQuote] ASC, [QuoteRev] ASC)
);


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,
    [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,
    [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) NULL,
    [HoleNumDies]     INT             NULL,
    [DiesPrice]       DECIMAL (18, 6) NULL,
    [DiesExpLife]     DECIMAL (18, 6) NULL,
    [DiesEOLife]      DECIMAL (18, 6) 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 (18, 6) 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,
    CONSTRAINT [PK_QuoteFull_Q_1] PRIMARY KEY CLUSTERED ([QuoteType] ASC, [CodQuote] ASC, [QuoteRev] 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].[test]...';


GO
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)
);


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].[QuoteList]...';


GO
CREATE TABLE [dbo].[QuoteList] (
    [QuoteType]    CHAR (1)        NOT NULL,
    [CodQuote]     BIGINT          NOT NULL,
    [QuoteRev]     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              (([CodItem] + '-') + [RawMat]),
    [Note]         NVARCHAR (2500) NOT NULL,
    [PriceOff]     DECIMAL (9, 6)  NOT NULL,
    [OrdDate]      DATE            NULL,
    [OrdNum]       NVARCHAR (50)   NOT NULL,
    [OrdRow]       NVARCHAR (50)   NOT NULL,
    [OrdPrice]     DECIMAL (9, 6)  NOT NULL,
    CONSTRAINT [PK_QuoteList_1] PRIMARY KEY CLUSTERED ([QuoteType] ASC, [CodQuote] ASC, [QuoteRev] 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].[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              (datediff(second, [EventStart], [EventEnd]) / (3600.00)) 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].[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].[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              (isnull([KgTeo], (0)) / CASE isnull([Duration], (1)) WHEN (0) THEN (1) ELSE isnull([Duration], (1)) END),
    [ScTec]        AS              ((1) - [KgTeo] / CASE [KgLor] WHEN (0) THEN (1) ELSE [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].[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].[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]([Active] ASC, [CodDiesGroup] ASC)
    INCLUDE([CodItem]) WHERE ([Active]=(0));


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].[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]     INT            NULL,
    [TotIn]      INT            NULL
);


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


GO
CREATE CLUSTERED INDEX [i_TabDifett_ProcessNum_KeyAMI]
    ON [dbo].[TabDifett]([ProcessNum] ASC, [KeyAMI] ASC);


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


GO
CREATE NONCLUSTERED INDEX [i_TabDifett_KeyAMI_ProcessNum]
    ON [dbo].[TabDifett]([KeyAMI] ASC, [ProcessNum] ASC)
    INCLUDE([TotOUT], [TotIn]);


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].[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].[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].[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             ((1) / ((1) - [WSR])),
    [MCR]        AS             ((1) / ((1) - [MSR])),
    [DCR]        AS             ((1) / ((1) - [DSR])),
    [valid]      BIT            NOT NULL,
    CONSTRAINT [PK_QuoteWorkInt] PRIMARY KEY CLUSTERED ([QuoteType] ASC, [CodQuote] ASC, [QuoteRev] ASC, [NumWI] ASC)
);


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 [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 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_QuoteFull_Q_PriceOff...';


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


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_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_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_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_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_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_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_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_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_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_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_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_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 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_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_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_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_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_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_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_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 [dbo].[f_getSubstring]...';


GO




-- ================================================================
-- Author     : Steamware
-- Create date: 2017-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_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_getNewCodQuote]...';


GO
-- =============================================
-- Author:		S.E.Locatelli
-- Create date: 2014.02.21
-- Description:	Retituisce un codice offerta valido da yyMMdd + incr
-- =============================================
CREATE FUNCTION 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') + '%'

	RETURN @output

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


GO



-- =============================================
-- Author:		Steamware
-- Create date: 2014-01-30
-- Description:	Ritorna l'imballo e i dati associati
-- =============================================
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)
		-- 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 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 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_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_QuoteFull_Q]...';


GO
CREATE VIEW dbo.v_QuoteFull_Q
AS
SELECT        Vers, QuoteType, CodQuote, QuoteRev, CodClient, ClientName, CodItem, CodItemGroup, RawMat, UnitWeight, BatchQty, CodInco, KeyAM, Note, PriceOff, CodClientAssoc, ClientNameAssoc, ItemDescr, 
                         CodifProfilo, ClasseMerc, TipoDies, CodDiesGroup, DiamDies, HoleNumDies, DiesPrice, DiesExpLife, DiesEOLife, 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, FVC + FC4UG01 + OH4UG01 + FC4UG04 - PriceOff AS NetMar, (PriceOff - FVC) / (FC4UG01 + OH4UG01 + FC4UG04) AS FCShield, (PRMWeight - PTare) 
                         * (PriceOff + RawMatFullCost) / PWeight AS PckSur
FROM            dbo.QuoteFull_Q
GO
PRINT N'Creating [dbo].[v_selClient]...';


GO
CREATE VIEW dbo.v_selClient
AS
SELECT        CodClient AS value, ClientName + ' [' + CodClient + ']' AS label
FROM            dbo.ClientDet
WHERE        (CodClient <> '')
GO
PRINT N'Creating [dbo].[v_selItems]...';


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


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]
(
	@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)),
        -- campi calcolati
        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 )
            ,   ( @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', @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(100) , @NumSMED ) )
               ,( @QuoteType, @CodQuote, @QuoteRev, '01', 'KgTeo'     , CONVERT(NVARCHAR(100) , @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

		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

		-- 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	#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.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

		-- 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 
       		-- (E) Calcolo price/life!
		    SET	@DiesPriceLife = @DiesPrice / @DiesEOLife
          END
        ELSE 
		  BEGIN
			SET @DiesPriceLife = 0   -- metto a zero il DiesPriceLife
			SET @valid = 0           -- indico che valore non è valido  ( ND excel )
		  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)
        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) )

		/*************************************************************
		* 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)
		VALUES ( @QuoteType, @CodQuote, @QuoteRev, '01', @CodPlant, 'VENDITA', @RawMat, @BatchQty, @SellCostF01 * @BatchQty, @SSR )
		-- inserisco costi per ROTTAME
              ,( @QuoteType, @CodQuote, @QuoteRev, '01', @CodPlant, 'ROTTAME', @RawMat, @BatchQty, @RefCostF01 * @BatchQty, 1 - @SSR )
		-- inserisco costi per VENDITA
              ,( @QuoteType, @CodQuote, @QuoteRev, '04', @CodPlant, 'VENDITA', @RawMat, @BatchQty, @SellCostF04 * @BatchQty, @SSR )
		-- inserisco costi per ROTTAME
		      ,( @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)
		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 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_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

	BEGIN TRAN

		SET NOCOUNT ON;

		-- svuoto tabella...
		TRUNCATE TABLE TabDifett

		-- riempio di nuovo valori!
		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
	
		-- 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_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_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 + '%')
GO
PRINT N'Creating [dbo].[stp_QL_fullDataSearch]...';


GO
-- =============================================
-- STORED PROCEDURE stp_QL_fullDataSearch
--
-- Author:		Steamware
-- Create 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) = ''
	)
AS
SET NOCOUNT ON

-- calcolo con aggiunta campi sommati...
SELECT *	
FROM v_QuoteFull_Q
WHERE CodClient = CASE WHEN ISNULL(@CodClient,'') = '' THEN CodClient ELSE @CodClient END
	AND CodItem = CASE WHEN ISNULL(@CodItem,'') = '' THEN CodItem ELSE @CodItem END
	AND RawMat = CASE WHEN ISNULL(@RawMat,'') = '' THEN RawMat ELSE @RawMat END

RETURN
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_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_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/gestioen 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 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
		, PkgDesc
		, PRMWeight
		, PWeight
		, PTare
		, TareStRatio
        , LivPackage
        , LivPackageDett
	    )
  ) 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.CodClient
	, CD.ClientName
	, QL.CodItem
	, QL.CodItemGroup
	, QL.RawMat
	, QL.UnitWeight
	, QL.BatchQty
	, QL.CodInco
	, QL.KeyAM
	, QL.Note
	, QL.PriceOff
	, pQP.CodClientAssoc
	, pQP.ClientNameAssoc
	, pQP.ItemDescr
	, pQP.CodifProfilo
	, pQP.ClasseMerc
	, pQP.TipoDies
	, pQP.CodDiesGroup
	, pQP.DiamDies
	, pQP.HoleNumDies
	, pQP.DiesPrice
	, pQP.DiesExpLife
	, pQP.DiesEOLife
	, pQP.NumDiesInList
	, pQP.NumDiesExaust
	, pQP.CodPlant
	, pQP.KeyAMIL
	, pQP.KgTeo
	, pQP.NumSMED
	, pQP.QuotaMan
	, pQP.PRMWeight
	, pQP.PWeight
	, pQP.PTare
    , pQP.LivPackage
    , pQP.LivPackageDett
	, 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

INTO #TempFullData        -- carico in temp table
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

---- 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

IF @QuoteType = 'Q' 
 BEGIN 
    IF OBJECT_ID('QuoteFull_Q') IS NULL             -- DROP TABLE QuoteFull_Q
        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 dbo.QuoteFull_Q 
        SELECT * FROM #TempFullData
     END
 END

ELSE IF @QuoteType = 'R'
 BEGIN 
    IF OBJECT_ID('QuoteFull_R') IS NULL             -- DROP TABLE QuoteFull_R
        SELECT * INTO dbo.QuoteFull_R FROM #TempFullData
    ELSE
     BEGIN
        INSERT dbo.QuoteFull_R
        SELECT * FROM #TempFullData
     END
 END

ELSE IF @QuoteType = 'S'
 BEGIN 
    IF OBJECT_ID('QuoteFull_S') IS NULL             -- DROP TABLE QuoteFull_S
        SELECT * INTO dbo.QuoteFull_S FROM #TempFullData
    ELSE
     BEGIN     
        INSERT dbo.QuoteFull_S
        SELECT * FROM #TempFullData
     END
 END

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

RETURN
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_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

	BEGIN TRAN

		SET NOCOUNT ON;

		-- svuoto tabella...
		TRUNCATE TABLE TabProdSc

		-- riempio di nuovo valori!
		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
	
		-- 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
		(
			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
		)
		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_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

	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_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_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',
--	@CodQuote			BIGINT	= 0,
--	@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

-- variabili
DECLARE	@CodQuote		BIGINT	= 0,
		@QuoteRev		INT		= 0

BEGIN TRAN

	-- calcolo nuovo record odierno
	SELECT	@CodQuote = dbo.f_getNewCodQuote()

	-- inserisco riga in QuoteList
	INSERT INTO QuoteList(QuoteType, CodQuote, QuoteRev, CodClient, CodItem, UnitWeight, CodItemGroup, RawMat, CodInco, Note)
	SELECT      @QuoteType, @CodQuote, @QuoteRev, @CodClient, CodItem, UnitWeight, 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)

COMMIT TRAN

-- ricalcolo!
EXEC stp_QL_fullDataUpdate @QuoteType
		,@CodQuote
		,@QuoteRev
        ,'Y'

-- seleziono intera riga!
	
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_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

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_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 [voc].[stp_insNewLemma]...';


GO
/*************************************
* STORED PROCEDURE stp_insNewLemma
*
*  elimina record anagrafica classe prodotto
*
* mod : 14/05/2012	
* aut : S.E. Locatelli
**************************************/
CREATE PROCEDURE [voc].[stp_insNewLemma]
(
	@lemma		NVARCHAR(50),
	@traduzione NVARCHAR(500)
)
AS

-- elimino se c'era già...
DELETE
FROM		Vocabolario
WHERE		lemma = @lemma

-- 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 [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_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;

        -- =======================================
		-- 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;

        -- =================================================
		-- Carico i dati dei GRUPPI DI MATRICI ( DiesGroupDet )
        -- nel caso debbano essere integrati vanno caricati nella tabella ext.DiesGroupRaw
        -- =================================================
		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 = '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;


		---- 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_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_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_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) VALUES (CodPlant, ProcessNum)
			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_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, '#### - ' + 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_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_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 [tmp].[importClientsRaw]...';


GO


-- =============================================
-- Author:		S.E. Locatelli
-- Create 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].[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].[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].[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 [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

EXEC stp_QL_fullDataUpdate @QuoteType
	, @CodQuote
	, @QuoteRev
	, @DoUpdate

---- 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_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_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'
	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_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].[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].[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].[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].[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].[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].[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].[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].[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].[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].[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].[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].[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].[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].[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 (0-100)', @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].[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].[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].[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 = 0
         Left = 0
      End
      Begin Tables = 
         Begin Table = "QuoteFull_Q"
            Begin Extent = 
               Top = 6
               Left = 38
               Bottom = 136
               Right = 221
            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_QuoteFull_Q';


GO
PRINT N'Creating [dbo].[v_QuoteFull_Q].[MS_DiagramPaneCount]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_DiagramPaneCount', @value = 1, @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'VIEW', @level1name = N'v_QuoteFull_Q';


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 = 4290
         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].[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 [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 [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
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
