Ошибка oracle 00942

Because this post is the top one found on stackoverflow when searching for «ORA-00942: table or view does not exist insert», I want to mention another possible cause of this error (at least in Oracle 12c): a table uses a sequence to set a default value and the user executing the insert query does not have select privilege on the sequence. This was my problem and it took me an unnecessarily long time to figure it out.

To reproduce the problem, execute the following SQL as user1:

create sequence seq_customer_id;

create table customer (
c_id number(10) default seq_customer_id.nextval primary key,
name varchar(100) not null,
surname varchar(100) not null
);

grant select, insert, update, delete on customer to user2;

Then, execute this insert statement as user2:

insert into user1.customer (name,surname) values ('michael','jackson');

The result will be «ORA-00942: table or view does not exist» even though user2 does have insert and select privileges on user1.customer table and is correctly prefixing the table with the schema owner name. To avoid the problem, you must grant select privilege on the sequence:

grant select on seq_customer_id to user2;

ORA-00942

ORA-00942: таблица или обзор не существуют

Причина:

Вводимая таблица или обзор не существует, или происходит ссылка на обзор когда требуется таблица. Существующие пользовательские таблицы не могут просматриваться запрашиванием словаря данных.

Действие:

Убедитесь, что спеллинг вашей таблицы или обзора правилен, не надо указывать таблицу где требуется обзор. Вводите всегда имя существующей таблицы или обзора.

Have you gotten an ORA-00942 error? I’ll explain the cause and the solution of the error in this article.

ORA-00942 Cause

The error message appears when you try to run an SQL statement:

ORA-00942: table or view does not exist

This happens for one of many reasons:

  • The statement references a table or view that does not exist
  • You do not have access to that table or view
  • The table or view belongs to a different schema and you did not refer to the schema name
  • You’re running Oracle 12c, using a sequence as a default value, but don’t have select privileges on the sequence.

The cause of the error should be the same in each database version. It shouldn’t matter if you’re getting this “table or view does not exist” error in Oracle 10g, Oracle 11g, or Oracle 12c.

The only difference is the sequence-related cause mentioned above because one of the new features in Oracle 12c is the ability to use a sequence as a default value.

Let’s take a look at some of the solutions, depending on the cause.

There are several solutions for this error, depending on the cause.

First, check that the table exists. You can do that by running this query:

SELECT owner, object_name, object_type
FROM all_objects
WHERE object_type IN ('TABLE','VIEW')
AND object_name = 'OBJECT_NAME';

Substitute the word OBJECT_NAME with your table name. It must be in upper case as well.

SELECT owner, object_name, object_type
FROM all_objects
WHERE object_type IN ('TABLE','VIEW')
AND object_name = 'CLASS';

Results:

OWNER OBJECT_NAME OBJECT_TYPE
SYSTEM CLASS TABLE

If your table does not show, then it does not exist, and you’ll need to look into why it doesn’t exist.

Or, if you’re using SQL Developer, you can check the table exists by expanding the Tables section on the left side of the screen. If you see the table there, it means it exists and you’re the owner.

Class Table in Tree Explorer

Next, check the owner of the table.

If the table exists, and you’re getting this error, then check the owner of the table.

You can use the same query as above, and take note of the owner of the table.

If the owner is not you, then you’ll need to contact the database administrator to request privileges to select from the table (or to perform whatever operation you were trying to do).

Finally, check your query to ensure it refers to the correct schema.

If the table or view exists, and you have the privileges you need, then it could be an issue in your query.

Let’s say your username is “bob”. You have a set of tables under the “bob” schema.

If you want to select from a table called “employee”, and this is in the “mary” schema, it is owned by “mary”. When you refer to the table (such as in a SELECT statement), you might have a query like this:

SELECT *
FROM employee;

You might get the ORA-00942 error at this point. This is because Oracle is looking in your schema, or “bob”, for an employee table. But, it doesn’t exist in your schema – it’s in the “mary” schema.

So, you’ll need to change your query to include the schema name.

SELECT *
FROM mary.employee;

This query should run without the error.

Oracle 12c and Sequences

If you’re getting the ora-00942 table or view does not exist in Oracle 12c, then it could be caused by this situation:

  • Another user has a table and a sequence
  • One of the columns in the table has a default value of the sequence.nextval
  • You have the right privileges on the table

However, you can get this error if you’re querying this table and don’t have select privileges on the sequence.

Consider this situation:

As user “bob”:

CREATE SEQUENCE sequence_book_id;

CREATE TABLE books (
  book_id NUMBER(5) DEFAULT sequence_book_d.nextval PRIMARY KEY,
  title VARCHAR2(100)
);

GRANT SELECT, INSERT, UPDATE, DELETE ON books TO "mary";

Now, logged in as “mary”:

INSERT INTO books (title)
VALUES ('The Adventure');

You’ll get an ORA-00942 error here.

The reason for this is that “mary” doesn’t have SELECT privileges on sequence_book_id. She has INSERT privileges on the table, but as a result of inserting into the table, a SELECT on the sequence is called, which causes this error.

To resolve this, grant SELECT privileges to the second user.

GRANT SELECT ON sequence_book_id TO mary;

That should now work.

I hope this article has helped you resolve the ORA-00942 error.

While you’re here, if you want an easy-to-use list of the main features in Oracle SQL, get my SQL Cheat Sheet here:

For my Oracle database I created a user. I want that user to have access to only 3 tables. So I wrote those queries:

grant select on table1 to newuser;
grant select on table2 to newuser;
grant select on table3 to newuser;

And I got this from the console, which ensures that I gave the grant.

GRANT succeeded

However when I connect to database with this user and write the following query, I get ORA-00942 error.

Select * from table1;

I think I need to write additional queries for privileges and roles(I already added CONNECT role). What might it be?

asked Jun 23, 2014 at 10:42

brainmassage's user avatar

brainmassagebrainmassage

1,2347 gold badges23 silver badges42 bronze badges

1

Run the query by specifying table owner.

Select * from tableowner.table1;

If this doesn’t work then either you have not granted access on correct table or you are logged in with wrong user.

remember same table name can exist in multiple schemas.

answered Jun 23, 2014 at 10:46

Lokesh's user avatar

Assume that,

  • NEWUSER —> THE user to which a grant has been provided.

  • EXISTINGUSER —> The owner of the table for which a grant is provided.

Login as EXISTINGUSER, and enter following query:

GRANT SELECT ON TABLE1 TO NEWUSER ;

Login as NEWUSER, and select using:

SELECT * FROM EXISTINGUSER.TABLE1;

In case you want to avoid using «EXISTINGUSER».»TABLE1″, then you can create a synonym, which is equivalent to a ALIAS NAME:

Login as NEWUSER, enter following query:

CREATE SYNONYM SYN_TABLE1 FOR EXISTINGUSER.TABLE1;

For selecting data from synonym, login as NEWUSER and select using:

SELECT * FROM SYN_TABLE1;

Synonym Reference: http://docs.oracle.com/cd/B19306_01/server.102/b14200/statements_7001.htm

answered Jun 23, 2014 at 11:00

ngrashia's user avatar

ngrashiangrashia

9,8395 gold badges43 silver badges58 bronze badges

Вы иногда видите ошибку ora-00942 при выполнении оператора SQL. У нее есть несколько причин, и, как обычно, синтаксис ошибки не самый описательный. Если вы столкнулись с этим и хотите знать, как исправить ошибку ora-00942, читайте дальше.

Насколько я знаю, существует три основные причины ошибки ora-00942:

  1. Недостаточные привилегии пользователя
  2. Таблица или представление фактически не существует
  3. Таблица или представление находится в другой схеме

Я покажу вам, как устранить каждую из них.

как исправить ошибку ora-00942

Исправление ошибки ora-00942

Прежде всего, небольшая оговорка. Я не DBA, я администратор Windows и техник по настольному и серверному оборудованию. Я знаю, как запускать SQL, но не до такой степени, и уж точно не до такого уровня, чтобы устранять неполадки. Мне пришлось обратиться за помощью к моему приятелю Oracle DBA, поэтому, хотя я написал эту статью, все умные части принадлежат ему.

Этот список трех причин ошибки ora-00942 не является исчерпывающим. Существуют и другие случайные причины ее возникновения, но эти три, по-видимому, являются наиболее распространенными.

Недостаточные привилегии пользователя

Одной из основных причин ошибки ora-00942 является то, что пользователь не имеет достаточных привилегий для доступа к данной таблице. Вы можете проверить это, выполнив два запроса.

 – list system privileges for the user or role SELECT * FROM dba_sys_privs WHERE grantee IN (&user_role, 'PUBLIC');

— list object privileges for the user or role

SELECT grantee, owner||'.'||table_name object, privilege, grantable FROM dba_tab_privs WHERE grantee IN (&user_role) ORDER BY grantee, owner||'.'||table_name, privilege;

Эти два запроса скажут вам, есть ли у пользователя нужные привилегии для выполнения команды. Если у пользователя есть нужные привилегии, переходите к следующему пункту. Если у пользователя нет нужных привилегий, предоставьте ему их или попросите администратора БД сделать это.

Ошибка ora-00942 также может возникнуть, если пользователь используемой схемы имеет привилегии INSERT, но не имеет привилегий SELECT. Опять же, проверьте уровень привилегий и добавьте SELECT в список или попросите администратора БД сделать это. Очевидно, что специфическая привилегия SELECT должна быть предоставлена каждой схеме, иначе вы все равно увидите ошибку ora-00942.

как исправить ошибку ora-00942

Таблица или представление фактически не существует

Эта причина ошибки ora-00942 может быть вызвана неправильным синтаксисом запроса или если таблица не существует. Хотя это кажется логичным первым пунктом, с которого следует начать, я уверен, что привилегии пользователя являются причиной ошибки номер один. Отсутствие таблицы или использование неправильного синтаксиса таблицы — вторая.

Чтобы проверить, существует ли таблица, сначала проверьте синтаксис запроса. Если синтаксис правильный, запустите этот запрос.

SELECT owner, object_name, object_type FROM all_objects WHERE object_type IN ('TABLE','VIEW') AND object_name = ‘YOUR_TABLE_NAME';

В последней строке вставьте фактическое имя таблицы, где вы видите ‘YOUR_TABLE_NAME’. Это должно точно сказать вам, существует ли таблица, которую вы пытаетесь запросить, или нет. Если таблица не возвращается, значит таблица, которую вы запрашиваете, не существует в схеме или базе данных.

Если в системе, которую вы используете, есть меню Tables, вы можете вручную проверить наличие таблицы, если хотите, но вышеприведенный запрос сделает свою работу.

Таблица или представление находится в другой схеме

Если у пользователя есть привилегии и таблица существует, а вы все еще видите ошибку ora-00942, это, скорее всего, связано со схемой. Если вы управляете несколькими схемами, легко запустить запрос к чужой схеме. Когда вы заняты и сталкиваетесь с этим, это простая ошибка.

Проверьте схему вручную, если можете, или добавьте имя схемы в строку FROM вашего запроса. Если у вас нет правильных привилегий для новой схемы, вы снова увидите ошибку ora-00942. Вернитесь к первому варианту исправления привилегий пользователя и проверьте соответствующую схему или попросите вашего DBA сделать это за вас.

Как упоминалось выше, я консультировался с моим приятелем Oracle DBA для написания этой статьи, так что вся заслуга за тяжелую работу принадлежит ему. Если вы найдете здесь какие-либо ошибки или упущения, они принадлежат только мне. Дайте мне знать в разделе комментариев, если я что-то упустил или неправильно понял, и я это исправлю.

Если вы знаете другой способ исправить ошибку ora-00942, расскажите нам об этом ниже!

YouTube видео: Как исправить ошибку ora-00942


Понравилась статья? Поделить с друзьями:
  • Ошибка ora 6512
  • Ошибка ora 39002
  • Ошибка ora 32004
  • Ошибка ora 305500
  • Ошибка ora 28040