在包含数据的同时修改表格列,从数字到varchar2直接

时间:2018-03-31 18:46:08

标签: sql oracle oracle11g sqlplus

我有两张桌子:

CREATE TABLE vendedores (
    cedula      NUMBER(11) NOT NULL,
    nombre      VARCHAR2(30) NOT NULL,
    apellido    VARCHAR2(30) NOT NULL,
    telefono    VARCHAR2(15) NOT NULL,
    direccion   VARCHAR2(60) NOT NULL,
    CONSTRAINT pk_vendedores PRIMARY KEY ( cedula )
)
TABLESPACE basedtp;

CREATE TABLE ventas (
    id                NUMBER(8) NOT NULL,
    id_cliente        NUMBER(8) NOT NULL,
    fecha             DATE NOT NULL,
    numero_factura    NUMBER(8) NOT NULL,
    monto_total       NUMBER(9) NOT NULL,
    plazo             NUMBER(2) NOT NULL,
    tipo              VARCHAR2(2) NOT NULL,
    cedula_vendedor   NUMBER(11) NULL,
    id_sucursal       NUMBER(2) NULL,
    CONSTRAINT pk_ventas PRIMARY KEY ( id ),
    CONSTRAINT fk_ventas_clientes FOREIGN KEY ( id_cliente )
        REFERENCES clientes ( id )
            ON DELETE CASCADE,
    CONSTRAINT fk_ventas_vendedores FOREIGN KEY ( cedula_vendedor )
        REFERENCES vendedores ( cedula )
            ON DELETE CASCADE,
    CONSTRAINT fk_ventas_sucursal FOREIGN KEY ( id_sucursal )
        REFERENCES sucursal ( id_sucursal )
            ON DELETE CASCADE
)
TABLESPACE basedtp;

如果我有一些数据,例如:

INSERT INTO vendedores (
    cedula,
    nombre,
    apellido,
    telefono,
    direccion
) VALUES (
    '4993886',
    'nombre_vendedor_01',
    'apellido_vendedor_01',
    'telefono01',
    'direccion_vendedor_01'
);

INSERT INTO ventas (
    id,
    id_cliente,
    fecha,
    numero_factura,
    monto_total,
    plazo,
    tipo,
    cedula_vendedor,
    id_sucursal
) VALUES (
    '1',
    '1',
    SYSDATE,
    '1',
    '100000',
    '1',
    't1',
    '4993886',
    '1'
);

之后我需要像这样修改cedula和cedula_vendedor列:

ALTER TABLE vendedores MODIFY
    cedula VARCHAR2(11);

ALTER TABLE ventas MODIFY
    cedula_vendedor VARCHAR2(11);

但是我收到以下错误:

Error starting at line : 276 in command -
ALTER TABLE vendedores MODIFY
    cedula VARCHAR2(11)
Error report -
ORA-02267: column type incompatible with referenced column type
02267. 00000 -  "column type incompatible with referenced column type"
*Cause:    The datatype of the referencing column is incompatible with the

Error starting at line : 279 in command -
ALTER TABLE ventas MODIFY
    cedula_vendedor VARCHAR2(11)
Error report -
ORA-02267: column type incompatible with referenced column type
02267. 00000 -  "column type incompatible with referenced column type"
*Cause:    The datatype of the referencing column is incompatible with the

嗯,我知道我可以使用varchar2数据类型创建一个辅助列并传递所有数据,删除旧列并再次创建约束但是没有更直接的方法来重新定义列?

1 个答案:

答案 0 :(得分:1)

错误消息是由表CONSTRAINT fk_ventas_vendedores FOREIGN KEY ( cedula_vendedor ) REFERENCES vendedores ( cedula )中的ventas引起的。

ALTER语句之前添加以下drop constraint语句,您将得到另一个错误:“要修改的列必须为空才能更改数据类型”。

ALTER TABLE ventas DROP CONSTRAINT fk_ventas_vendedores;

请参阅:Oracle SQL to change column type from number to varchar2 while it contains data