-- SET @pbi_datetime = '2018-01-01 10:00:10'
-- SET @db_date_time = '2018-01-01 10:00:10';

-- POPULATE fact_comment
select @max_inserted_at:=coalesce(max(stg_inserted_at), FROM_UNIXTIME(1)) from dim_address_details;

insert into dim_address_details
(`address_id`,
  `firstname`,
  `lastname`,
  `middlename`,
  `prefix`,
  `suffix`,
  `company_name`,
  `street`,
  `email`,
  `telephone`,
  `vat_id`,
  `stg_inserted_at`,
  `inserted_at`)
select
 s.order_address_id as `address_id`,
  s.`firstname`,
  s.`lastname`,
  s.`middlename`,
  s.`prefix`,
  s.`suffix`,
  s.`company` as `company_name`,
  s.`street`,
  s.`email`,
  s.`telephone`,
  s.`vat_id`,
  s.`inserted_at` AS `stg_inserted_at`,
  @db_date_time as inserted_at
 from bim_stg_order_address s
 left join dim_address_details dim on dim.address_id = s.order_address_id
 where s.inserted_at >= @max_inserted_at AND dim.address_id is null;

-- {{IF_ANALYZE}}dim_address_details{{/IF_ANALYZE}}