USE [HCITools]
GO

IF EXISTS (SELECT * FROM sys.objects o JOIN sys.schemas s ON o.schema_id = s.schema_id WHERE o.name = 'Retrieve_Data_Interbase' AND OBJECTPROPERTY(object_id,N'IsProcedure') = 1 AND s.name = 'dba')
  DROP PROCEDURE [dba].[Retrieve_Data_Interbase]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO





CREATE PROCEDURE [dba].[Retrieve_Data_Interbase]
                 
AS 
/*=============================================================================

  Explication du traitement realise par la SP
  -------------------------------------------
    Cette SP est executee tous les jours et effectue le rattrapage des donnees entre SUNCENT et AMACENT par rapport a une table.

	1: Recuperation du login et de la date
    2: Reprise des top 40 000 de la table [HCItools].[dba].[TT_AMR_interbase_to_retrieve] et isTreated = 0 puis mise en table temporaire
    3: Curseur sur la table temporaire avec le distinct table name
    4: Dummy update sur les records concernes sur SUNCENT
    5: Update AMR (AMR_type_of_change = 2) selon variables @currentlogin et @currentdate et current SPID
    6: Flag is isTreated = 1 sur la table [HCItools].[dba].[TT_AMR_interbase_to_retrieve]
        
  Parametres  
  ----------  
   
  Creation : 28.04.2021 / SPE
   
  Modifications : 
  
=============================================================================*/ 

SET NOCOUNT ON;

/*------------------- Declaration des variables --------------------*/

DECLARE @errno               int,
        @errmsg              varchar(255),
		@tableName           varchar(60),
        @currentlogin        sysname,
        @currentdate         datetime,
		@pkname              sysname,
		@pktype              sysname,
		@colName             varchar(255)



/*-------------------------- Traitement ---------------------------*/
BEGIN TRY

/* 1: Recuperation du login et de la date */
SET @currentlogin = SYSTEM_USER
SET @currentdate = getdate()

/* 2: Reprise des top 40 000 de la table [HCItools].[dba].[TT_AMR_interbase_to_retrieve] et isTreated = 0 puis mise en table temporaire */
CREATE TABLE #TT_current_AMR([AMRREF_AMR_table_name] [varchar](60) NULL,[AMRREF_row_ID] [int] NULL,[AMRREF_AMR_row_GUID] [varchar](60) NULL)

INSERT INTO #TT_current_AMR([AMRREF_AMR_table_name],[AMRREF_row_ID],[AMRREF_AMR_row_GUID])
SELECT TOP 40000 [AMRREF_AMR_table_name],[AMRREF_row_ID],[AMRREF_AMR_row_GUID] FROM [HCItools].[dba].[TT_AMR_interbase_to_retrieve] WHERE IsTreated = 0  ORDER BY [AMRREF_AMR_APS_TS]

/* 3: Curseur sur la table temporaire avec le distinct table name */
DECLARE c_alltables CURSOR LOCAL FORWARD_ONLY STATIC FOR
SELECT AMRREF_AMR_table_name
  FROM #TT_current_AMR
 GROUP BY AMRREF_AMR_table_name 
 ORDER BY AMRREF_AMR_table_name
;
OPEN c_alltables
;
FETCH NEXT FROM c_alltables
  INTO @tableName
;
WHILE @@fetch_status = 0
BEGIN

SET @Colname = NULL

  /* 4: Dummy update sur les records concernes sur SUNCENT */

  /* get target PK column name and type */
  select @pkname = c.[name], @pktype =col.data_type
        from arizona.sys.tables t with (nolock)
        join arizona.sys.indexes i with (nolock)
          on i.[object_id] = t.[object_id]
         and i.is_primary_key = 1
        join arizona.sys.index_columns ic with (nolock)
          on ic.index_id = i.index_id
         and ic.[object_id] = i.[object_id]
        join arizona.sys.[columns] c with (nolock)
          on c.[object_id] = ic.[object_id] 
         and c.column_id = ic.column_id
		 join arizona.INFORMATION_SCHEMA.COLUMNS col
		   on col.column_name = c.name
		   and col.table_name = t.[name]
       where t.[name] = @tableName;

      SELECT TOP 1 @Colname = COLUMN_NAME
            FROM arizona.information_schema.columns
           WHERE table_name = @tableName
            AND DATA_TYPE = 'bit'
            AND IS_NULLABLE = 'NO'
	
	        IF @Colname is null
	        BEGIN
            SELECT TOP 1 @Colname = COLUMN_NAME
              FROM arizona.information_schema.columns
             WHERE table_name = @tableName
               AND CHARACTER_MAXIMUM_LENGTH > 0
               AND IS_NULLABLE = 'NO'
             ORDER BY CHARACTER_MAXIMUM_LENGTH ASC
          END
 
          IF @Colname is null
          BEGIN
            SELECT TOP 1 @Colname = COLUMN_NAME
              FROM arizona.information_schema.columns
             WHERE table_name = @tableName
               AND DATETIME_PRECISION is not null
               AND IS_NULLABLE = 'NO'	 
	        END

          IF @Colname is null
          BEGIN
            SELECT TOP 1 @Colname = COLUMN_NAME
              FROM arizona.information_schema.columns
             WHERE table_name = @tableName
               AND NUMERIC_PRECISION is not null
	             AND IS_NULLABLE = 'NO'
	             AND COLUMN_NAME <> @PKname
	        END
   
  if @pktype = 'int'
  BEGIN

    /* dummy update */
    EXEC('UPDATE prod
  SET prod.' + @Colname +' = prod.' + @Colname +'
   FROM #TT_current_AMR tt
   JOIN arizona.dbo.' + @tableName +' prod
     ON tt.AMRREF_row_ID = prod.' + @pkname +'
  WHERE tt.AMRREF_AMR_table_name = ''' + @tableName + '''')

  END
  ELSE
  BEGIN

    /* dummy update */
    EXEC('UPDATE prod
  SET prod.' + @Colname +' = prod.' + @Colname +'
   FROM #TT_current_AMR tt
   JOIN arizona.dbo.' + @tableName +' prod
     ON tt.AMRREF_AMR_row_GUID = prod.' + @pkname +'
  WHERE tt.AMRREF_AMR_table_name = ''' + @tableName + '''')

  END

  FETCH NEXT FROM c_alltables
    INTO @tableName
  ;
END
;
CLOSE c_alltables
;
DEALLOCATE c_alltables

/* 5: Update AMR (AMR_type_of_change = 2) selon variables @currentlogin et @currentdate et current SPID */
UPDATE arizona.dbo.aps_monitor_row
   SET AMR_type_of_change = 2
 WHERE AMR_APS_TS >= @currentdate
   AND AMR_system_user = @currentlogin
   AND AMR_SQL_spid = @@SPID
   AND AMR_type_of_change IN (0,1)

/* 6: Flag is isTreated = 1 sur la table [HCItools].[dba].[TT_AMR_interbase_to_retrieve] */
UPDATE TTAMR
   SET isTreated = 1
  FROM [HCItools].[dba].[TT_AMR_interbase_to_retrieve] TTAMR
  JOIN #TT_current_AMR TT
    ON TT.AMRREF_AMR_table_name = TTAMR.AMRREF_AMR_table_name
	AND TT.AMRREF_row_ID = TTAMR.AMRREF_row_ID

UPDATE TTAMR
   SET isTreated = 1
  FROM [HCItools].[dba].[TT_AMR_interbase_to_retrieve] TTAMR
  JOIN #TT_current_AMR TT
    ON TT.AMRREF_AMR_table_name = TTAMR.AMRREF_AMR_table_name
	AND TT.AMRREF_AMR_row_GUID = TTAMR.AMRREF_AMR_row_GUID

DROP TABLE #TT_current_AMR

END TRY
BEGIN CATCH 
  SELECT @errno = 70003,
         @errmsg = 'error on Retrieve_Data_Interbase! ' + error_message()
  goto error_99
END CATCH; 

/*------------------ Retour au programme appelant -----------------*/

RETURN(@@error);

/*---------------------- Traitement des erreurs ----------------------*/
error_99:
  RAISERROR (@errmsg, 16, 1);
  RETURN(@errno);


GO
