DROP VIEW IF EXISTS V_ENTITYHISTORY
GO

CREATE VIEW V_ENTITYHISTORY AS
SELECT
   e.ID
  ,e.C_ENTITYID
  ,e.C_ENTITYNAME
  ,e.C_ALTERATIONDATE
  ,e.C_REASON
  ,e.C_FELHASZNALOID
  ,e.C_INTEZMENYID
  ,e.C_TANEVID
  ,CASE WHEN ev.C_ENTITYATTRIBUTEHISTORYID IS NULL THEN ea.C_ORIGINALVALUE ELSE ev.C_ORIGINALVALUE END AS C_ORIGINALVALUE
  ,CASE WHEN ev.C_ENTITYATTRIBUTEHISTORYID IS NULL THEN ea.C_CURRENTVALUE ELSE ev.C_CURRENTVALUE END AS C_CURRENTVALUE
  ,ea.C_PROPERTYNAME
FROM T_ENTITYHISTORY e WITH(NOLOCK)
  LEFT JOIN T_ENTITYATTRIBUTEHISTORY ea WITH(NOLOCK) ON e.ID = ea.C_ENTITYHISTORYID
  LEFT JOIN T_ENTITYBLOBVALUES ev WITH(NOLOCK) ON ev.C_ENTITYATTRIBUTEHISTORYID = ea.ID
