How to add a Primary Key on a Oracle view? [duplicate]

强颜欢笑 提交于 2019-12-06 13:43:53

The SQL standard unfortunately only permits UNIQUE and PRIMARY KEY constraints on base tables, not views. Oracle permits unique indexes on materialized views but not on views generally.

The only thing that comes in my mind is using a materialized view and then create a unique index on it:

drop materialized view tq84_mat_view;
drop table tq84_table;
create table tq84_table (
  a number,
  b number
);

create materialized view tq84_mat_view 
refresh on commit as
select 
  a,
  sum(b) sum_b
from 
  tq84_table
group by
  a;

create unique index tq84_mat_view_uix on tq84_mat_view (sum_b);

insert into tq84_table values (1, 1);
insert into tq84_table values (2, 2);
insert into tq84_table values (1, 4);

commit;

insert into tq84_table values (2, 3);

commit;
--> ORA-12008: error in materialized view refresh path
--> ORA-00001: unique constraint (SPEZMDBA.TQ84_MAT_VIEW_UIX) violated

While this might be useful, it must be kept in mind that the materialized view, as opposed to a "normal" view occupies space in a tablespace. And of course, the index needs space, too.

This is the way by which you can add a primary key in your view.

CREATE OR REPLACE FORCE VIEW VU_NAME
        (
          PRIMARY_KEY, NAME_ID, ADDRESS_ID
         )
        AS 
        SELECT DISTINCT ROWNUM AS PRIMARY_KEY,
            NAME.ID UNIT_ID,
            ADDRESS_ID
        from table1;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!