有时候在oracle数据库创建视图时会遇到:ora-01031:insufficient privileges错误,我也多次碰到了各种创建视图出错的情况,很多时候也没有太在意,今天被一同事问起这个问题,顺便总结一下出错的各种场景。
场景1:使用sys或system账号登陆数据库,创建dm、ods账号(授予connect、resource角色)
在另外一个窗口,以dm账号登录数据库
创建测试表test,并插入数据。然后创建该表对应的视图v_dm_test时报ora-01031: insufficient privileges
结论:在这个场景出现这个错误,是因为账号dm并没有授予创建视图的权限。需要授予dm账号创建视图的权限。以sys/system等具有dba权限的账号登陆数据库,授予dm账号创建视图的权限。
场景2:在上面的场景中,在ods账号下创建test_ods表并插入数据。然后授权select给dm用户,然后在dm用户下创建视图
先删除视图v_ods_test,然后收回用户dm创建视图的权限。
然后在dm下创建视图时会出现场景一的错误,
但是即使dm没有创建视图的权限了,我依然可以在sys用户下创建dm下视图
场景3: 在上面场景中,我们依然给予dm账号创建视图的权限,然后按如下步骤去测试
创建角色role_select_test,然后将表test_view的查询权限授予该角色,最后将该角色授予dm用户
但是在dm用户下,创建视图时报错。
这时,如果显示将表ods.test_view的查询权限授予dm后,就可以创建视图。
结论:
创建create view 的时候,是不可以利用相应的role隐式授权的,必须显式的授予这个对象相应的权限。metalink解释如下:
reason:under sql, if a user can select another user's table
and has the privilege to create a view, then the create view works.
yet, a create view on the other user's table generates ora-01031 if the
select privilege has been granted to a role and not directly.
官方文档关于创建视图的权限:
privileges required to create views
to create a view, you must meet the following requirements:
you must have been granted the
create view (to create a view in your schema) or create any view (to
create a view in another user's schema) system privilege, either
explicitly or through a role.
you must have been explicitly
granted the select, insert, update, or delete object privileges on all
base objects underlying the view or the select any table, insert any
table, update any table, or delete any table system privileges. you may
not have obtained these privileges through roles.
additionally, in order to grant
other users access to your view, you must have received object
privilege(s) to the base objects with the grant option option or
appropriate system privileges with the admin option option. if you have
not, grantees cannot access your view."