微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Oracle 从 varray 更改列数据类型

如何解决Oracle 从 varray 更改列数据类型

在 Oracle 数据库中,我有两个模式和两个相互镜像的表,除了两个表中的一列都是数字,但在模式 A 中它是 A.VARRAY,在模式 B 中它是 {{1 }}。

因此,我无法在表之间迁移数据,因为它们具有不一致的数据类型

有没有办法在不丢失数据的情况下将列数据类型从 B.VARRAY 更改为 A.varray

解决方法

只需使用cast(col as B.VARRAYTYPE)

SQL> CREATE OR REPLACE TYPE V_TYPE_1 AS VARRAY(5000) OF NUMBER(1);
  2  /

Type created.

SQL> CREATE OR REPLACE TYPE V_TYPE_2 AS VARRAY(5000) OF NUMBER(1);
  2  /

Type created.

SQL> create table t1 (a V_TYPE_1);

Table created.

SQL> insert into t1 values(v_type_1(1,2,3,4,5));

1 row created.

SQL> create table t2 (a V_TYPE_2);

Table created.

SQL> insert into t2 select cast(a as v_type_2) from t1;

1 row created.

SQL> select * from t2;

A
-------------------------
V_TYPE_2(1,5)

1 row selected.
,

CAST 是的,我同意萨彦的观点。不过,由于涉及到两个用户,因此需要一些中间步骤 - grant execute on type 是最重要的,我想说。这是一个例子。

我的用户是 scottmike。它们中的每一个都有相同的表描述。 scott 应该将行插入到 mike 的表中。

连接为 scott

SQL> show user
USER is "SCOTT"
SQL> create or replace type v_type as varray(5000) of number(1);
  2  /

Type created.

SQL> create table test (id number,a v_type);

Table created.

SQL> insert into test(id,a) values (1,v_type(1));

1 row created.

SQL>

Connected as mike:使用与 scott 相同的类型:

SQL> show user
USER is "MIKE"
SQL> create or replace type v_type as varray(5000) of number(1);
  2  /

Type created.

SQL> create table test (id number,a v_type);

Table created.

SQL> grant insert on test to scott;

Grant succeeded.

SQL>

作为 scott 连接,尝试将行插入到 mike 的表中:

SQL> show user
USER is "SCOTT"
SQL> insert into mike.test (id,a) select id,a from test;
insert into mike.test (id,a from test
                                         *
ERROR at line 1:
ORA-00932: inconsistent datatypes: expected MIKE.V_TYPE got SCOTT.V_TYPE

让我们试试CAST

SQL> insert into mike.test (id,cast(a as mike.v_type) from test;
insert into mike.test (id,cast(a as mike.v_type) from test
                                                   *
ERROR at line 1:
ORA-00904: : invalid identifier


SQL>

为了使其工作,mike 必须授予执行对他们的类型scott

SQL> show user
USER is "MIKE"
SQL> grant execute on v_type to scott;

Grant succeeded.

SQL>

最后,它有效

SQL> show user
USER is "SCOTT"
SQL> insert into mike.test (id,cast(a as mike.v_type) from test;

1 row created.

SQL>
,

您是否愿意向其中一个表添加一列,用另一列的值填充新列,比如通过更新语句,然后删除旧列?

T1(c1 V_TYPE_1); T2(c1 V_TYPE_2);

(1) 向 T2 添加列: T2(c1 V_TYPE_2,c2 V_TYPE_1);

(2) 更新 T2,使 c1 和 c2 每一行的值都相同。

(3) 从 T2 中删除旧列: T2(c2 V_TYPE_1);

如果表不活动,这个解决方案会更容易一些。如果表处于活动状态,您将需要添加一个触发器,以便两列同步。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。