declare
    object_exists exception;
    pragma exception_init (object_exists , -00955);
begin
  execute immediate
	'CREATE TABLE PTOVTA_EMPRESA_CONTABANCARIA (
	  PTOVTAEMPRESACONTABANCARIA_ID NUMBER(7) NOT NULL,
	  PTOVTAEMPRESA_ID NUMBER(7) NOT NULL,
	  EMPRESACONTABANCARIA_ID NUMBER(7) NOT NULL,
	  ACTIVO NUMBER(1),
	  FECMODIF DATE,
	  USUARIO_ID NUMBER(7),
	  CONSTRAINT PTOVTAEMPCONBAN_PK PRIMARY KEY (PTOVTAEMPRESACONTABANCARIA_ID) ENABLE)';
	  
  execute immediate 
	'CREATE SEQUENCE PTOVTAEMPCONBAN_SEQ INCREMENT BY 1 START WITH 1 NOCACHE ORDER NOCYCLE';	
	
  exception when object_exists then null;
end;
/

declare
    dup_val_on_index  exception;
    pragma exception_init (dup_val_on_index  , -00001);
begin
  execute immediate 
    'insert into PTOVTA_EMPRESA_CONTABANCARIA (PTOVTAEMPRESACONTABANCARIA_ID, PTOVTAEMPRESA_ID, EMPRESACONTABANCARIA_ID, ACTIVO, FECMODIF, USUARIO_ID) 
     select PTOVTAEMPCONBAN_SEQ.nextval, PTOVTAEMPRESA_ID, EMPRESACONTABANCARIA_ID, ACTIVO, FECMODIF, USUARIO_ID from (
       select PTOVTAEMPRESA_ID, EMPRESACONTABANCARIA_ID, ACTIVO, FECMODIF, USUARIO_ID from PTOVTA_EMPRESA where EMPRESACONTABANCARIA_ID is not null)';

  exception when dup_val_on_index  then null;
end;
