CREATE TABLE ORGRELACOPER (
    ID               NUMBER        NOT NULL,
    NRORGOPER        NUMBER        NOT NULL,
    CDOPERADOR       VARCHAR2(12)  NOT NULL,
    IDATIVO          VARCHAR2(1)   DEFAULT 'S' NOT NULL,
    NRORG            NUMBER 	   DEFAULT SYS_CONTEXT('nrorg_ctx','nrorg') NOT NULL,
    DTINCLUSAO       DATE          DEFAULT SYSDATE,
    DTULTATU         DATE          DEFAULT SYSDATE,
    NRORGINCLUSAO    NUMBER        DEFAULT SYS_CONTEXT('nrorg_ctx','nrorg')	NULL,
    CDOPERINCLUSAO   VARCHAR2(12)  DEFAULT '1' NULL,
    NRORGULTATU      NUMBER        DEFAULT SYS_CONTEXT('nrorg_ctx','nrorg')	NULL,
    CDOPERULTATU     VARCHAR2(12)  DEFAULT '1',
    CONSTRAINT PK_ORGRELACOPER          PRIMARY KEY(ID),
    CONSTRAINT FK_ORGRELACOPER_OPER     FOREIGN KEY (CDOPERADOR) REFERENCES OPERADOR (CDOPERADOR),
    CONSTRAINT CKC_IDATIVO_ORGRELACOPER CHECK (IDATIVO IN ('S','N'))
)
/
INSERT INTO ORGRELACOPER (SELECT DISTINCT ROWNUM AS ID, O.NRORGOPER, O.CDOPERADOR, 'S' AS IDATIVO,
                                 O.NRORG, SYSDATE AS DTINCLUSAO, SYSDATE AS DTULTATU, 1, 1, 1, 1
                            FROM OPERADOR O
                           WHERE O.NRORGOPER IS NOT NULL
                             AND O.NRORGOPER <> 1
                             AND NOT EXISTS (SELECT R.ID 
                                               FROM ORGRELACOPER R
                                              WHERE R.NRORGOPER = O.NRORGOPER
                                                AND R.CDOPERADOR = O.CDOPERADOR
                                                AND R.NRORG = O.NRORG))
/
COMMIT
/