select
    'ORGANISATION_PARENT' as relation_type,
    'ORGANISATION' as from_entity_type,
    cast(o.oid as varchar(128)) as from_source_entity_id,
    'ORGANISATION' as to_entity_type,
    cast(o.n_rekey01 as varchar(128)) as to_source_entity_id,
    o.VertragGiltAb as valid_from,
    o.gueltigbis as valid_to,
    cast(null as datetime) as source_updated_at,
    'I_90021' as source_table,
    cast(o.oid as varchar(128)) as source_row_id
from dbo.I_90021 o
where o.n_rekey01 is not null

union all

select
    'DRIVER_ORGANISATION' as relation_type,
    'DRIVER' as from_entity_type,
    cast(rel.ID_Driver as varchar(128)) as from_source_entity_id,
    'ORGANISATION' as to_entity_type,
    cast(rel.ID_I_90021 as varchar(128)) as to_source_entity_id,
    rel.GILT_AB as valid_from,
    rel.GILT_BIS as valid_to,
    rel.LastUpdate as source_updated_at,
    'Driver_I_90021' as source_table,
    cast(rel.ID as varchar(128)) as source_row_id
from dbo.Driver_I_90021 rel

union all

select
    'DRIVER_CARD_DRIVER' as relation_type,
    'DRIVER_CARD' as from_entity_type,
    cast(c.ID as varchar(128)) as from_source_entity_id,
    'DRIVER' as to_entity_type,
    cast(c.ID_Driver as varchar(128)) as to_source_entity_id,
    c.IssueDate as valid_from,
    c.ExpiryDate as valid_to,
    cast(null as datetime) as source_updated_at,
    'Card' as source_table,
    cast(c.ID as varchar(128)) as source_row_id
from dbo.Card c
where c.ID_Driver is not null

union all

select
    'VEHICLE_ORGANISATION' as relation_type,
    'VEHICLE_REGISTRATION' as from_entity_type,
    cast(rel.ID_Vehicle as varchar(128)) as from_source_entity_id,
    'ORGANISATION' as to_entity_type,
    cast(rel.ID_I_90021 as varchar(128)) as to_source_entity_id,
    rel.GILT_AB as valid_from,
    rel.GILT_BIS as valid_to,
    rel.LastUpdate as source_updated_at,
    'Vehicle_I_90021' as source_table,
    cast(rel.ID as varchar(128)) as source_row_id
from dbo.Vehicle_I_90021 rel

union all

select
    'VEHICLE_REGISTRATION_VEHICLE' as relation_type,
    'VEHICLE_REGISTRATION' as from_entity_type,
    cast(v.ID as varchar(128)) as from_source_entity_id,
    'VEHICLE' as to_entity_type,
    cast(v.ID_VehicleIdentification as varchar(128)) as to_source_entity_id,
    v.ValidFrom as valid_from,
    v.ValidTo as valid_to,
    cast(null as datetime) as source_updated_at,
    'Vehicle' as source_table,
    cast(v.ID as varchar(128)) as source_row_id
from dbo.Vehicle v
where v.ID_VehicleIdentification is not null
