USE CCR;
GO

SET NOCOUNT ON;
SET XACT_ABORT ON;

SET ANSI_NULLS ON;
SET QUOTED_IDENTIFIER ON;
GO

IF DB_NAME() <> 'CCR'
BEGIN
    RAISERROR('Wrong database.', 16, 10);
    RETURN;
END;
GO

IF NOT EXISTS (
       SELECT *
       FROM   sys.objects
       WHERE  [object_id] = OBJECT_ID(N'[dbo].[plib_new_version]')
              AND [type] IN (N'P', N'PC')
   )
BEGIN
    EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[plib_new_version] AS';
END;
GO

ALTER PROCEDURE dbo.plib_new_version(
    @ModelPath       VARCHAR(MAX),
    @ModelImplID     INT OUTPUT,
    @debug           BIT = 0
)
AS
BEGIN
	SET NOCOUNT ON;
	
	DECLARE @NodeID                      INT,
	        @IsShared                    INT,
	        @OwnerID                     INT,
	        @Hidden                      INT,
	        @ModelId                     INT,
	        @Old_ModelImplID             INT,	--if @ModelImplentationExists = 1 - old ModelImplID value
	        @ModelName                   VARCHAR(MAX),
	        @Description                 VARCHAR(MAX) = 'Created with procedure plib_new_version',
	        @Cdatetime                   DATETIME = GETDATE(),
	        @FolderID                    INT,
	        @ModelImplentationExists     BIT = 0,
	        @ModelExists                 BIT = 0,
	        @Cdate                       VARCHAR(100) = CONVERT(VARCHAR(10), GETDATE(), 103 /*or 101*/) + ' ' +
	        LTRIM(RIGHT(CONVERT(VARCHAR(20), GETDATE(), 22), 11)),
	        @IndexBackSlash              INT,
	        @RealModelPath               VARCHAR(MAX);
	
	DECLARE @OutputTableId AS TABLE (ID INT);
	
	SET @IndexBackSlash = CHARINDEX('\', REVERSE(@ModelPath));
	SET @RealModelPath = (
	        SELECT REVERSE(
	                   SUBSTRING(
	                       REVERSE(@ModelPath),
	                       @IndexBackSlash + 1,
	                       LEN(REVERSE(@ModelPath))
	                   )
	               )
	    );	
	
	SET @ModelName = dbo.gsf_GetRestOfLineAfterLast(@ModelPath, '\');    
	
	EXEC dbo.plib_force_folder @RealModelPath,
	     @FolderID OUTPUT,
	     @debug;
	
	IF EXISTS (
	       SELECT *
	       FROM   dbo.Model AS mi
	       WHERE  mi.NodeID = @FolderID
	              AND mi.Name = @ModelName
	   )
	BEGIN
	    SELECT @ModelExists = 1;
	END;
	
	IF @ModelExists = 1
	BEGIN
	    SELECT @ModelID = mi.ModelID
	    FROM   dbo.Model AS mi
	    WHERE  mi.NodeID = @FolderID
	           AND mi.Name = @ModelName;
	    
	    IF EXISTS (
	           SELECT *
	           FROM   dbo.ModelImpl AS mi
	           WHERE  mi.ModelID = @ModelID
	       )
	    BEGIN
	        SET @ModelImplentationExists = 1;
	    END;
	END;
	
	--If model not exist in table dbo.Model then create it and get modelId:
	IF @ModelExists = 0
	BEGIN
	    SELECT @NodeID = m.NodeID,
	           @IsShared     = m.IsShared,
	           @OwnerID      = m.OwnerID,
	           @Hidden       = m.[Hidden]
	    FROM   dbo.ModelTree AS m
	    WHERE  m.NodeID = @FolderID;
	    
	    INSERT INTO [dbo].[Model]
	      (
	        [Name],
	        [NodeID],
	        [AdminID],
	        [SupervisorID],
	        [TV],
	        [ActiveModelImplID],
	        [IsShared],
	        [OwnerID],
	        [Description],
	        [ModelType],
	        [Hidden],
	        [RevisionInterval],
	        [NotifyByMail],
	        [NotifyByMessage]
	      )OUTPUT INSERTED.ModelID INTO @OutputTableId(ID)
	    VALUES
	      (
	        @ModelName,
	        @NodeID,
	        1,
	        1,
	        '',
	        NULL,	--now it's null then we must update it
	        @IsShared,
	        @OwnerID,
	        @Description + ' Date:' + @Cdate,
	        1,
	        @Hidden,
	        0,
	        0,
	        0
	      );
	    --remembered the last inserted identity when model not exists
	    SELECT @ModelID = (
	               SELECT TOP 1
	                      o.ID
	               FROM   @OutputTableId AS o
	           );
	    
	    DELETE FROM @OutputTableId;
	END;
	ELSE
	--If model exist in table dbo.Model then get it ModelID and it's ModelImplID
	BEGIN
		IF @ModelImplentationExists = 1
		BEGIN
			SELECT TOP 1 @ModelImplID = m.ActiveModelImplID,
			       @Old_ModelImplID = m.ActiveModelImplID
			FROM   dbo.Model AS m
			WHERE  m.ModelID = @ModelId
			
			IF @ModelImplID IS NULL
			BEGIN
			    SELECT TOP 1 @ModelImplID = mi.ModelImplID,
			           @Old_ModelImplID = mi.ModelImplID
			    FROM   dbo.ModelImpl AS mi
			    WHERE  mi.ModelID = @ModelID
			    ORDER BY
			           mi.VerMajor DESC,
			           mi.VerMinor DESC;
			END;
		END;
	END;
	
	IF @debug = 1
	BEGIN
	    SELECT @FolderID [@FolderID],
	           @ModelImplentationExists [@ModelImplentationExists],
	           @ModelExists [@ModelExists],
	           @ModelImplID [@ModelImplID],
	           @ModelID [@ModelID],
	           @Old_ModelImplID [@Old_ModelImplID],
	           @RealModelPath [@RealModelPath];
	END;
	
	--create new ModelImplentation 
	IF @ModelImplentationExists = 1
	BEGIN
	    INSERT INTO [dbo].[ModelImpl]
	      (
	        [ModelID],
	        [VerMajor],
	        [VerMinor],
	        [AuthorID],
	        [StateRank],
	        [PosMessage],
	        [NegMessage],
	        [NumberOfClasses],
	        [NumberOfCluster],
	        [AccuracyEstimation],
	        [TP],
	        [FP],
	        [ChangeDescription],
	        [TransformationModelName],
	        [TransformationModel],
	        [ClassificationModelName],
	        [DateCreated],
	        [ECRType],
	        [ECRAbRatio],
	        [ECRMaxError],
	        [STaskBiasingMode],
	        [STaskValue],
	        [STaskNonCases],
	        [STaskCases],
	        [SamplingType],
	        [SamplingBegin],
	        [SamplingEnd],
	        [SamplingRandomOrder],
	        [ValidationMode],
	        [SamplingValue],
	        [GoS],
	        [CountRecsUsedForClustering],
	        [CountRecsUsedForValidation],
	        [ModelerPrj],
	        [TransformerPrj],
	        [ScriptTable],
	        [RuleParams]
	      )OUTPUT INSERTED.ModelImplID INTO @OutputTableId(ID)
	    SELECT ModelId,
	           mi.[VerMajor],
	           (
	               SELECT r.max_VerMinor + 1 VerMinor
	               FROM   (
	                          SELECT MAX(mi.VerMinor) max_VerMinor
	                          FROM   dbo.ModelImpl AS mi
	                          WHERE  mi.ModelID = @ModelId
	                      ) r
	           ),
	           mi.[AuthorID],
	           mi.[StateRank],
	           mi.[PosMessage],
	           mi.[NegMessage],
	           mi.[NumberOfClasses],
	           mi.[NumberOfCluster],
	           mi.[AccuracyEstimation],
	           mi.[TP],
	           mi.[FP],
	           @Description,
	           mi.[TransformationModelName],
	           mi.[TransformationModel],
	           mi.[ClassificationModelName],
	           @Cdatetime,
	           mi.[ECRType],
	           mi.[ECRAbRatio],
	           mi.[ECRMaxError],
	           mi.[STaskBiasingMode],
	           mi.[STaskValue],
	           mi.[STaskNonCases],
	           mi.[STaskCases],
	           mi.[SamplingType],
	           mi.[SamplingBegin],
	           mi.[SamplingEnd],
	           mi.[SamplingRandomOrder],
	           mi.[ValidationMode],
	           mi.[SamplingValue],
	           mi.[GoS],
	           mi.[CountRecsUsedForClustering],
	           mi.[CountRecsUsedForValidation],
	           mi.[ModelerPrj],
	           mi.[TransformerPrj],
	           mi.ScriptTable,
	           mi.[RuleParams]
	    FROM   dbo.ModelImpl AS mi
	    WHERE  mi.ModelImplID = @ModelImplID
	           AND mi.ModelID = @ModelId;
	    
	    --remembered the last inserted identity when model not exists
	    SELECT @ModelImplID = (
	               SELECT TOP 1
	                      o.ID
	               FROM   @OutputTableId AS o
	           );
	    
	    DELETE FROM @OutputTableId;
	    
	    --UPDATE dbo.Model
	    --SET    ActiveModelImplID = NULL
	    --WHERE  Model.ModelID = @ModelId;
	END;
	ELSE
	BEGIN
		INSERT INTO [dbo].[ModelImpl]
		  (
		    [ModelID],
		    [VerMajor],
		    [VerMinor],
		    [AuthorID],
		    [StateRank],
		    [PosMessage],
		    [NegMessage],
		    [NumberOfClasses],
		    [NumberOfCluster],
		    [AccuracyEstimation],
		    [TP],
		    [FP],
		    [ChangeDescription],
		    [TransformationModelName],
		    [TransformationModel],
		    [ClassificationModelName],
		    [DateCreated],
		    [ECRType],
		    [ECRAbRatio],
		    [ECRMaxError],
		    [STaskBiasingMode],
		    [STaskValue],
		    [STaskNonCases],
		    [STaskCases],
		    [SamplingType],
		    [SamplingBegin],
		    [SamplingEnd],
		    [SamplingRandomOrder],
		    [ValidationMode],
		    [SamplingValue],
		    [GoS],
		    [CountRecsUsedForClustering],
		    [CountRecsUsedForValidation],
		    [ModelerPrj],
		    [TransformerPrj],
		    [ScriptTable],
		    [RuleParams]
		  )OUTPUT INSERTED.ModelImplID INTO @OutputTableId(ID)
		VALUES
		  (
		    @ModelId,
		    1,
		    1,
		    1,
		    9,
		    'YES',
		    'NO',
		    0,
		    0,
		    0,
		    NULL,
		    NULL,
		    @Description,
		    ' ',
		    '<?xml version="1.0" encoding="UTF-8" ?>' + CHAR(10) + '<script-model><name>DUMMY</name>' + CHAR(10) +
		    CHAR(10) + '<scripts/>' + CHAR(10) + '<fields/>' + CHAR(10) + '</script-model>' + CHAR(10) + CHAR(10),
		    ' ',
		    @Cdatetime,
		    NULL,
		    NULL,
		    NULL,
		    NULL,
		    NULL,
		    NULL,
		    NULL,
		    NULL,
		    NULL,
		    NULL,
		    NULL,
		    NULL,
		    NULL,
		    NULL,
		    NULL,
		    NULL,
		    NULL,
		    NULL,
		    '',
		    '<?xml version=''1.0'' encoding=''iso-8859-1'' ?><RuleParams version="2" cm="1"><items/><pitems/><sitems/><pragms/></RuleParams>'
		  );
		
		--remembered the last inserted identity when model not exists
		SELECT @ModelImplID = (
		           SELECT TOP 1
		                  o.ID
		           FROM   @OutputTableId AS o
		       );
		
		DELETE FROM @OutputTableId;
		
		UPDATE dbo.Model
		SET    ActiveModelImplID = NULL
		WHERE  Model.ModelID = @ModelId;
	END;
	
	--check ModelField for old ModelImpl 
	IF EXISTS (
	       SELECT *
	       FROM   dbo.ModelField mf
	       WHERE  mf.ModelImplID = @Old_ModelImplID
	   )
	   AND @ModelImplentationExists = 1
	BEGIN
	    --copy values from old ModelField (where mf.ModelImplID = @Old_ModelImplID)
	    --to new @ModelImplID
	    INSERT INTO dbo.ModelField
	      (
	        --ModelFieldID -- this column value is auto-generated
	        ModelImplID,
	        FieldName,
	        FieldType,
	        MinValue,
	        MaxValue,
	        ConstValue,
	        [Description]
	      )
	    SELECT @ModelImplID,
	           mf.FieldName,
	           mf.FieldType,
	           mf.MinValue,
	           mf.MaxValue,
	           mf.ConstValue,
	           mf.[Description]
	    FROM   dbo.ModelField AS mf
	    WHERE  mf.ModelImplID = @Old_ModelImplID;
	END;
END;
GO

USE plib_namecheck;
GO

SET NOCOUNT ON;
SET XACT_ABORT ON;

SET ANSI_NULLS ON;
SET QUOTED_IDENTIFIER ON;
GO

IF DB_NAME() <> 'plib_namecheck'
BEGIN
    RAISERROR('Wrong database.', 16, 10);
    RETURN;
END;
GO

IF NOT EXISTS (
       SELECT *
       FROM   sys.objects
       WHERE  [object_id] = OBJECT_ID(N'[dbo].[plib_new_version]')
              AND [type] IN (N'P', N'PC')
   )
BEGIN
    EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[plib_new_version] AS';
END;
GO

ALTER PROCEDURE dbo.plib_new_version(
    @ModelPath       VARCHAR(MAX),
    @ModelImplID     INT OUTPUT,
    @debug           BIT = 0
)
AS
BEGIN
	SET NOCOUNT ON;
	
	DECLARE @NodeID                      INT,
	        @IsShared                    INT,
	        @OwnerID                     INT,
	        @Hidden                      INT,
	        @ModelId                     INT,
	        @Old_ModelImplID             INT,	--if @ModelImplentationExists = 1 - old ModelImplID value
	        @ModelName                   VARCHAR(MAX),
	        @Description                 VARCHAR(MAX) = 'Created with procedure plib_new_version',
	        @Cdatetime                   DATETIME = GETDATE(),
	        @FolderID                    INT,
	        @ModelImplentationExists     BIT = 0,
	        @ModelExists                 BIT = 0,
	        @Cdate                       VARCHAR(100) = CONVERT(VARCHAR(10), GETDATE(), 103 /*or 101*/) + ' ' +
	        LTRIM(RIGHT(CONVERT(VARCHAR(20), GETDATE(), 22), 11)),
	        @IndexBackSlash              INT,
	        @RealModelPath               VARCHAR(MAX);
	
	DECLARE @OutputTableId AS TABLE (ID INT);
	
	SET @IndexBackSlash = CHARINDEX('\', REVERSE(@ModelPath));
	SET @RealModelPath = (
	        SELECT REVERSE(
	                   SUBSTRING(
	                       REVERSE(@ModelPath),
	                       @IndexBackSlash + 1,
	                       LEN(REVERSE(@ModelPath))
	                   )
	               )
	    );	
	
	SET @ModelName = dbo.gsf_GetRestOfLineAfterLast(@ModelPath, '\');    
	
	EXEC dbo.plib_force_folder @RealModelPath,
	     @FolderID OUTPUT,
	     @debug;
	
	IF EXISTS (
	       SELECT *
	       FROM   dbo.Model AS mi
	       WHERE  mi.NodeID = @FolderID
	              AND mi.Name = @ModelName
	   )
	BEGIN
	    SELECT @ModelExists = 1;
	END;
	
	IF @ModelExists = 1
	BEGIN
	    SELECT @ModelID = mi.ModelID
	    FROM   dbo.Model AS mi
	    WHERE  mi.NodeID = @FolderID
	           AND mi.Name = @ModelName;
	    
	    IF EXISTS (
	           SELECT *
	           FROM   dbo.ModelImpl AS mi
	           WHERE  mi.ModelID = @ModelID
	       )
	    BEGIN
	        SET @ModelImplentationExists = 1;
	    END;
	END;
	
	--If model not exist in table dbo.Model then create it and get modelId:
	IF @ModelExists = 0
	BEGIN
	    SELECT @NodeID = m.NodeID,
	           @IsShared     = m.IsShared,
	           @OwnerID      = m.OwnerID,
	           @Hidden       = m.[Hidden]
	    FROM   dbo.ModelTree AS m
	    WHERE  m.NodeID = @FolderID;
	    
	    INSERT INTO [dbo].[Model]
	      (
	        [Name],
	        [NodeID],
	        [AdminID],
	        [SupervisorID],
	        [TV],
	        [ActiveModelImplID],
	        [IsShared],
	        [OwnerID],
	        [Description],
	        [ModelType],
	        [Hidden],
	        [RevisionInterval],
	        [NotifyByMail],
	        [NotifyByMessage]
	      )OUTPUT INSERTED.ModelID INTO @OutputTableId(ID)
	    VALUES
	      (
	        @ModelName,
	        @NodeID,
	        1,
	        1,
	        '',
	        NULL,	--now it's null then we must update it
	        @IsShared,
	        @OwnerID,
	        @Description + ' Date:' + @Cdate,
	        1,
	        @Hidden,
	        0,
	        0,
	        0
	      );
	    --remembered the last inserted identity when model not exists
	    SELECT @ModelID = (
	               SELECT TOP 1
	                      o.ID
	               FROM   @OutputTableId AS o
	           );
	    
	    DELETE FROM @OutputTableId;
	END;
	ELSE
	--If model exist in table dbo.Model then get it ModelID and it's ModelImplID
	BEGIN
		IF @ModelImplentationExists = 1
		BEGIN
			SELECT TOP 1 @ModelImplID = m.ActiveModelImplID,
			       @Old_ModelImplID = m.ActiveModelImplID
			FROM   dbo.Model AS m
			WHERE  m.ModelID = @ModelId
			
			IF @ModelImplID IS NULL
			BEGIN
			    SELECT TOP 1 @ModelImplID = mi.ModelImplID,
			           @Old_ModelImplID = mi.ModelImplID
			    FROM   dbo.ModelImpl AS mi
			    WHERE  mi.ModelID = @ModelID
			    ORDER BY
			           mi.VerMajor DESC,
			           mi.VerMinor DESC;
			END;
		END;
	END;
	
	IF @debug = 1
	BEGIN
	    SELECT @FolderID [@FolderID],
	           @ModelImplentationExists [@ModelImplentationExists],
	           @ModelExists [@ModelExists],
	           @ModelImplID [@ModelImplID],
	           @ModelID [@ModelID],
	           @Old_ModelImplID [@Old_ModelImplID],
	           @RealModelPath [@RealModelPath];
	END;
	
	--create new ModelImplentation 
	IF @ModelImplentationExists = 1
	BEGIN
	    INSERT INTO [dbo].[ModelImpl]
	      (
	        [ModelID],
	        [VerMajor],
	        [VerMinor],
	        [AuthorID],
	        [StateRank],
	        [PosMessage],
	        [NegMessage],
	        [NumberOfClasses],
	        [NumberOfCluster],
	        [AccuracyEstimation],
	        [TP],
	        [FP],
	        [ChangeDescription],
	        [TransformationModelName],
	        [TransformationModel],
	        [ClassificationModelName],
	        [DateCreated],
	        [ECRType],
	        [ECRAbRatio],
	        [ECRMaxError],
	        [STaskBiasingMode],
	        [STaskValue],
	        [STaskNonCases],
	        [STaskCases],
	        [SamplingType],
	        [SamplingBegin],
	        [SamplingEnd],
	        [SamplingRandomOrder],
	        [ValidationMode],
	        [SamplingValue],
	        [GoS],
	        [CountRecsUsedForClustering],
	        [CountRecsUsedForValidation],
	        [ModelerPrj],
	        [TransformerPrj],
	        [ScriptTable],
	        [RuleParams]
	      )OUTPUT INSERTED.ModelImplID INTO @OutputTableId(ID)
	    SELECT ModelId,
	           mi.[VerMajor],
	           (
	               SELECT r.max_VerMinor + 1 VerMinor
	               FROM   (
	                          SELECT MAX(mi.VerMinor) max_VerMinor
	                          FROM   dbo.ModelImpl AS mi
	                          WHERE  mi.ModelID = @ModelId
	                      ) r
	           ),
	           mi.[AuthorID],
	           mi.[StateRank],
	           mi.[PosMessage],
	           mi.[NegMessage],
	           mi.[NumberOfClasses],
	           mi.[NumberOfCluster],
	           mi.[AccuracyEstimation],
	           mi.[TP],
	           mi.[FP],
	           @Description,
	           mi.[TransformationModelName],
	           mi.[TransformationModel],
	           mi.[ClassificationModelName],
	           @Cdatetime,
	           mi.[ECRType],
	           mi.[ECRAbRatio],
	           mi.[ECRMaxError],
	           mi.[STaskBiasingMode],
	           mi.[STaskValue],
	           mi.[STaskNonCases],
	           mi.[STaskCases],
	           mi.[SamplingType],
	           mi.[SamplingBegin],
	           mi.[SamplingEnd],
	           mi.[SamplingRandomOrder],
	           mi.[ValidationMode],
	           mi.[SamplingValue],
	           mi.[GoS],
	           mi.[CountRecsUsedForClustering],
	           mi.[CountRecsUsedForValidation],
	           mi.[ModelerPrj],
	           mi.[TransformerPrj],
	           mi.ScriptTable,
	           mi.[RuleParams]
	    FROM   dbo.ModelImpl AS mi
	    WHERE  mi.ModelImplID = @ModelImplID
	           AND mi.ModelID = @ModelId;
	    
	    --remembered the last inserted identity when model not exists
	    SELECT @ModelImplID = (
	               SELECT TOP 1
	                      o.ID
	               FROM   @OutputTableId AS o
	           );
	    
	    DELETE FROM @OutputTableId;
	    
	    --UPDATE dbo.Model
	    --SET    ActiveModelImplID = NULL
	    --WHERE  Model.ModelID = @ModelId;
	END;
	ELSE
	BEGIN
		INSERT INTO [dbo].[ModelImpl]
		  (
		    [ModelID],
		    [VerMajor],
		    [VerMinor],
		    [AuthorID],
		    [StateRank],
		    [PosMessage],
		    [NegMessage],
		    [NumberOfClasses],
		    [NumberOfCluster],
		    [AccuracyEstimation],
		    [TP],
		    [FP],
		    [ChangeDescription],
		    [TransformationModelName],
		    [TransformationModel],
		    [ClassificationModelName],
		    [DateCreated],
		    [ECRType],
		    [ECRAbRatio],
		    [ECRMaxError],
		    [STaskBiasingMode],
		    [STaskValue],
		    [STaskNonCases],
		    [STaskCases],
		    [SamplingType],
		    [SamplingBegin],
		    [SamplingEnd],
		    [SamplingRandomOrder],
		    [ValidationMode],
		    [SamplingValue],
		    [GoS],
		    [CountRecsUsedForClustering],
		    [CountRecsUsedForValidation],
		    [ModelerPrj],
		    [TransformerPrj],
		    [ScriptTable],
		    [RuleParams]
		  )OUTPUT INSERTED.ModelImplID INTO @OutputTableId(ID)
		VALUES
		  (
		    @ModelId,
		    1,
		    1,
		    1,
		    9,
		    'YES',
		    'NO',
		    0,
		    0,
		    0,
		    NULL,
		    NULL,
		    @Description,
		    ' ',
		    '<?xml version="1.0" encoding="UTF-8" ?>' + CHAR(10) + '<script-model><name>DUMMY</name>' + CHAR(10) +
		    CHAR(10) + '<scripts/>' + CHAR(10) + '<fields/>' + CHAR(10) + '</script-model>' + CHAR(10) + CHAR(10),
		    ' ',
		    @Cdatetime,
		    NULL,
		    NULL,
		    NULL,
		    NULL,
		    NULL,
		    NULL,
		    NULL,
		    NULL,
		    NULL,
		    NULL,
		    NULL,
		    NULL,
		    NULL,
		    NULL,
		    NULL,
		    NULL,
		    NULL,
		    NULL,
		    '',
		    '<?xml version=''1.0'' encoding=''iso-8859-1'' ?><RuleParams version="2" cm="1"><items/><pitems/><sitems/><pragms/></RuleParams>'
		  );
		
		--remembered the last inserted identity when model not exists
		SELECT @ModelImplID = (
		           SELECT TOP 1
		                  o.ID
		           FROM   @OutputTableId AS o
		       );
		
		DELETE FROM @OutputTableId;
		
		UPDATE dbo.Model
		SET    ActiveModelImplID = NULL
		WHERE  Model.ModelID = @ModelId;
	END;
	
	--check ModelField for old ModelImpl 
	IF EXISTS (
	       SELECT *
	       FROM   dbo.ModelField mf
	       WHERE  mf.ModelImplID = @Old_ModelImplID
	   )
	   AND @ModelImplentationExists = 1
	BEGIN
	    --copy values from old ModelField (where mf.ModelImplID = @Old_ModelImplID)
	    --to new @ModelImplID
	    INSERT INTO dbo.ModelField
	      (
	        --ModelFieldID -- this column value is auto-generated
	        ModelImplID,
	        FieldName,
	        FieldType,
	        MinValue,
	        MaxValue,
	        ConstValue,
	        [Description]
	      )
	    SELECT @ModelImplID,
	           mf.FieldName,
	           mf.FieldType,
	           mf.MinValue,
	           mf.MaxValue,
	           mf.ConstValue,
	           mf.[Description]
	    FROM   dbo.ModelField AS mf
	    WHERE  mf.ModelImplID = @Old_ModelImplID;
	END;
END;
GO
