-- Tables

-- Alters

update STOR.T_SGTINS set IdInvoiceItem = null where IdInvoiceItem is not null and not exists (select * from  STOR.T_INVOICE_ITEM where ElementId = IdInvoiceItem);

do $$ begin
IF EXISTS(select * from pg_indexes where schemaname ilike 'STOR' and tablename ilike 'T_SGTINS' and indexname ilike 'UQ_T_SGTINS_IdInvoiceItem')
THEN
drop index STOR.UQ_T_SGTINS_IdInvoiceItem;
END IF;
end; $$;
ALTER TABLE STOR.T_SGTINS DROP CONSTRAINT if exists UQ_T_SGTINS_IdInvoiceItem;
ALTER TABLE STOR.T_SGTINS DROP COLUMN if exists IdInvoiceItem_UQ;

CREATE UNIQUE INDEX UQ_T_SGTINS_IdInvoiceItem ON STOR.T_SGTINS(IdInvoiceItem);

ALTER TABLE STOR.T_SGTINS ADD CONSTRAINT FK_T_INVOICE_ITEM_T_SGTINS_IdInvoiceItem
FOREIGN KEY("idinvoiceitem") REFERENCES STOR.T_INVOICE_ITEM (ElementID);

