﻿IF OBJECT_ID('stage.sp_MrgDictionaryItemBase') IS NOT NULL BEGIN
  DROP PROCEDURE stage.sp_MrgDictionaryItemBase
END
GO

CREATE PROCEDURE stage.sp_MrgDictionaryItemBase 
AS
BEGIN
  MERGE stage.T_DICTIONARYITEMBASE_STAGE AS trg
  USING (
    SELECT 
      d.ID AS C_DICTIONARYITEMBASEID,
      NULL AS C_INTEZMENYID,
      MIN(d.C_NAME) AS C_NAME,
      MIN(d.C_TYPE) AS C_TYPE,
      te.C_NEV AS C_TANEVNEV,
      d.TOROLT
    FROM dbo.T_DICTIONARYITEMBASE d
      INNER JOIN dbo.T_TANEV te ON te.ID = d.C_TANEVID
    WHERE d.ID < 100000
      AND d.TOROLT = 'F' AND te.TOROLT = 'F'
      AND d.C_TYPE IN ('MunkaviszonyTipus', 'MunkakorTipus', 'Nem', 'MunkaviszonyTipus', 'Kepesites', 'TargyKategoriaTipus', 
        'EvfolyamTipus', 'CsoportTipus', 'EletpalyamodellFokozatTipus', 'MunkaidoKedvezmenyOka', 'OktatasiNevelesiFeladat', 'ESLAdatTipus', 'TeremTipus', 'OrszagTipus', 'KozteruletJelleg', 'FelvetelStatuszaTipus', 'TagozatTipus')
    GROUP BY d.ID, te.C_NEV, d.TOROLT
    UNION ALL
    SELECT 
      d.ID AS C_DICTIONARYITEMBASEID,
      d.C_INTEZMENYID AS C_INTEZMENYID,
      d.C_NAME AS C_NAME,
      d.C_TYPE AS C_TYPE,
      te.C_NEV AS C_TANEVNEV,
	    d.TOROLT
    FROM dbo.T_DICTIONARYITEMBASE d
      INNER JOIN dbo.T_TANEV te ON te.ID = d.C_TANEVID  AND te.TOROLT = 'F'
      INNER JOIN dbo.T_INTEZMENY i ON i.ID = d.C_INTEZMENYID AND i.TOROLT = 'F'
    WHERE d.ID >= 100000 
      AND d.TOROLT = 'F' AND te.TOROLT = 'F' AND i.TOROLT = 'F'
      AND d.C_TYPE IN ('MunkaviszonyTipus', 'MunkakorTipus', 'Nem', 'MunkaviszonyTipus', 'Kepesites', 'TargyKategoriaTipus', 
        'EvfolyamTipus', 'CsoportTipus', 'EletpalyamodellFokozatTipus', 'MunkaidoKedvezmenyOka', 'OktatasiNevelesiFeladat', 'ESLAdatTipus', 'TeremTipus', 'OrszagTipus', 'KozteruletJelleg', 'FelvetelStatuszaTipus', 'TagozatTipus')
  ) src ON src.C_DICTIONARYITEMBASEID = trg.C_DICTIONARYITEMBASEID AND src.C_TANEVNEV = trg.C_TANEVNEV
    WHEN MATCHED AND 
         (trg.C_NAME <> src.C_NAME OR (trg.C_NAME IS NULL AND src.C_NAME IS NOT NULL) OR (trg.C_NAME IS NOT NULL AND src.C_NAME IS NULL))
      OR (trg.C_TYPE <> src.C_TYPE OR (trg.C_TYPE IS NULL AND src.C_TYPE IS NOT NULL) OR (trg.C_TYPE IS NOT NULL AND src.C_TYPE IS NULL))
    THEN
      UPDATE SET
         trg.C_NAME = src.C_NAME
        ,trg.C_TYPE = src.C_TYPE
        ,trg.TOROLT = src.TOROLT
        ,trg.LASTCHANGED = GETDATE()
    WHEN NOT MATCHED BY TARGET THEN
      INSERT (
        C_DICTIONARYITEMBASEID,
        C_INTEZMENYID,
        C_NAME,
        C_TYPE,
        C_TANEVNEV,
        TOROLT,
        SERIAL,
        LASTCHANGED,
        CREATED
      ) VALUES (
        src.C_DICTIONARYITEMBASEID,
        src.C_INTEZMENYID,
        src.C_NAME,
        src.C_TYPE,
        src.C_TANEVNEV,
        src.TOROLT,
        0,
        GETDATE(),
        GETDATE()
      )
    WHEN NOT MATCHED BY SOURCE AND trg.TOROLT = 'F' THEN
      UPDATE SET 
        trg.LASTCHANGED = GETDATE(), 
        trg.TOROLT = 'T'
  ;
END
GO
