Ora 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 при выполнении оператора 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-00942

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

Причина:

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

Действие:

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

If you’ve used Oracle, you’ve probably gotten the helpful message «ORA-00942: Table or view does not exist». Is there a legitimate technical reason the message doesn’t include the name of the missing object?

Arguments about this being due to security sound like they were crafted by the TSA. If I’m an attacker, I’d know what table I just attempted to exploit, and be able to interpret this unhelpful message easily. If I’m a developer working with a complex join through several layers of application code, it’s often very difficult to tell.

My guess is that when this error was originally implemented, someone neglected to add the object name, and now, people are afraid it will break compatibility to fix it. (Code doing silly things like parsing the error message will be confused if it changes.)

Is there a developer-friendly (as opposed to recruiting your DBA) way to determine the name of the missing table?


Although I’ve accepted an answer which is relevant to the topic, it doesn’t really answer my question: Why isn’t the name part of the error message? If anyone can come up with the real answer, I’ll be happy to change my vote.

Lalit Kumar B's user avatar

Lalit Kumar B

47.3k13 gold badges96 silver badges123 bronze badges

asked Sep 5, 2008 at 17:45

erickson's user avatar

3

You can set an EVENT in your parameter file (plain text or spfile) to force Oracle to dump a detailed trace file in the user_dump_dest, the object name might be in there, if not the SQL should be.

EVENT=»942 trace name errorstack level 12″

If you are using a plain text file you need to keep all your EVENT settings on consecutive lines. Not sure how that applied to spfile.

answered Sep 5, 2008 at 17:51

Ethan Post's user avatar

Ethan PostEthan Post

3,0203 gold badges27 silver badges27 bronze badges

1

SQL*Plus does tell you the table that doesn’t exist. For example:

SQL> select
  2     *
  3  from
  4     user_tables a,
  5     non_existent_table b
  6  where
  7     a.table_name = b.table_name;
   non_existent_table b
   *
ERROR at line 5:
ORA-00942: table or view does not exist

Here it shows that the name of the missing table and the line number in the SQL statement where the error occurs.

Similarly, in a one-line SQL statement you can see the asterisk highlighting the name of the unknown table:

SQL> select * from user_tables a, non_existent_table b where a.table_name = b.table_name;
select * from user_tables a, non_existent_table b where a.table_name = b.table_name
                             *
ERROR at line 1:
ORA-00942: table or view does not exist

In terms of your question, I guess the reason the error message doesn’t include the name of the table is that the error message itself needs to be static text. The line number and location in the line of the error is clearly passed back to SQL*Plus (somehow).

answered Sep 9, 2008 at 15:11

Nick Pierpoint's user avatar

Nick PierpointNick Pierpoint

17.6k9 gold badges44 silver badges74 bronze badges

4

I would disagree with the opinion, that SQL+ lets you understand which table name is unacceptable. True, it helps in direct DML, although parsing it is very hard. But when it comes to dynamic, we get no help:

SQL> begin
  2  execute immediate 'insert into blabla values(1)';
  3  end;
  4  /
begin
*
ERROR at line 1:
ORA-00942: table or view does not exist
ORA-06512: at line 2

answered Jan 31, 2011 at 12:32

If you are using a SQL browsing tool like TOAD or TORA it will help you with ORA errors by highlightling or pointing moving the cursor to where you made your error.

Copy and paste your SQL in to one of these tools to help. You may also find the analyse info available useful too.

answered Sep 5, 2008 at 17:55

Mark Nold's user avatar

Mark NoldMark Nold

5,5987 gold badges30 silver badges33 bronze badges

1

If its not a huge statement, then the easiest way is just to check the data dictionary,

SQL> select * from xx,abc;
select * from xx,abc
                 *
ERROR at line 1:
ORA-00942: table or view does not exist


SQL> select owner,table_name from all_tables where table_name in ('XX','ABC');

OWNER                          TABLE_NAME
------------------------------ ------------------------------
MWATSON                        XX

SQL> 

This isn’t ideal, but short of going and examining trace files, I’m not sure how else to do it.

answered Sep 6, 2008 at 0:58

Matthew Watson's user avatar

Matthew WatsonMatthew Watson

14.1k9 gold badges61 silver badges82 bronze badges

I’ve never had a problem with interpreting Oracle error messages. Part of the reason is that every interactive tool I’ve seen for developing SQL for Oracle helpfully points to the location the query went wrong. That includes SQL*Plus, as others have noted, and the Perl DBI module:

$ exec_sql.pl 'select * from daul'
DBD::Oracle::db prepare failed: ORA-00942: table or view does not exist (DBD ERROR: error possibly near <*> indicator at char 14 in 'select * from <*>daul') [for Statement "select * from daul"] at exec_sql.pl line 68.

Well, that is a bit hard to read since it’s all squished on one line. But a GUI tool would be able to point to the token where Oracle started having problems with the query. And given a bit of work on a parser, you could write a tool to pick out the offending table.

To answer the underlying question, Oracle errors don’t seem to be designed to work the way you expect. As far as I can tell, none of the the error messages in Oracle support variable text. Instead, Oracle returns two bits of information: an error number and a location where the error occurs. If you have proper tools, it’s pretty easy to diagnose an error with those pieces of data. It can be argued that Oracle’s system is nicer to tool creators than one which provides variable amounts of diagnostic data depending on the error. Imagine having to write a custom parser for all of Oracle’s error messages (including future errors) to highlight the offending location.

Sometimes including the table name would be misleading. Just knowing where things went wrong can be a huge help:

SQL> select * from where dummy = 'X';
select * from where dummy = 'X'
              *
ERROR at line 1:
ORA-00903: invalid table name

As for why Oracle chose to do thing this way, I have some speculations:

  1. IBM used this style of error message for System R, which Larry Ellison, Bob Miner and Ed Oates copied to build Oracle V2. (Backward compatibility.)

  2. Error number and location are the smallest possible representation of diagnostic information. (Parsimony.)

  3. As I indicated above, to simplify the creation of tools that connect to Oracle. (Interoperability.)

In any case, I don’t think you need to be a DBA to figure out which table doesn’t exist. You just need to use the proper tools. (And adjust your expectations, I suppose.)

answered Apr 21, 2009 at 0:03

Jon Ericson's user avatar

Jon EricsonJon Ericson

20.8k12 gold badges97 silver badges147 bronze badges

6

Reason 1: Multi-lingual interface

There is a language-specific message configuration file for your database instance. Messages are pulled out of there and translated from the pure numeric version to the numeric+text version.

It was probably considered better to have the hardcoded strings, than to run the risk at runtime of having a mysterious failure due to an improperly formatted «%s» string.

(Not that I particularly agree with this POV, btw.)

Reason 2: Security

Right now you don’t particularly expose the internal workings of your application if you print a PHP, etc, dump of an Oracle error message to the browser.

Applications would be a bit more exposed if more detail were printed by default… For example, if citibank printed a more explanatory message.

(see disclaimer above, I would be happy to get more information in the error as well.)

answered Apr 21, 2009 at 3:54

Mark Harrison's user avatar

Mark HarrisonMark Harrison

295k124 gold badges328 silver badges464 bronze badges

1

@Matthew

Your query’s a start, but it might not work when you have multiple schemas. For example, if I log into our instance as myself, I have read access to all our tables. But if I don’t qualify the table name with the schema I’ll get an ORA-00942 for tables without synonyms:

SQL> select * from tools; 
select * from tools 
              * 
ERROR at line 1: 
ORA-00942: table or view does not exist 

The table still shows up in all_tables though:

SQL> select owner, table_name from all_tables where table_name = 'TOOLS'; 

OWNER                          TABLE_NAME 
------------------------------ ------------------------------ 
APPLICATION                    TOOLS 

@erikson
Sorry that doesn’t help much. I’m with Mark — I used TOAD.

answered Sep 7, 2008 at 13:07

Hobo's user avatar

HoboHobo

7,5065 gold badges39 silver badges50 bronze badges

ORA-00942 means that SQL engine found no table or view in your usable scope. In other words, table or view does not exist. The usable scope is a range which defines what tables and views you can use and how you can use them.

In reality, almost every SQL developers have ever seen the error before. The real causes of ORA-00942 may be varying from case to case though.

Now let’s take a look at some error patterns of ORA-00942 and their solutions described in the following sections.

  1. SELECT (Query)
  2. This may also apply to the following statements.

    • INSERT
    • UPDATE
    • DELETE
    • CREATE VIEW
    • GRANT SELECT ON
  3. ALTER TABLE
  4. This may also apply to the following statements.

    • DROP TABLE
    • ALTER TABLE ADD COLUMN
    • ALTER TABLE ADD CONSTRAINT
    • ALTER TABLE MOVE

SELECT (Query)

This may also apply to the following statements.

  • INSERT
  • UPDATE
  • DELETE
  • CREATE VIEW

Usually, we see ORA-00942 in SELECT statements. For example, we select a table which belongs to other user in SQL*Plus.

SQL> show user
USER is "SH"
SQL> select count(*) cnt from hr.lottery_list;
select count(*) cnt from hr.lottery_list
                            *
ERROR at line 1:
ORA-00942: table or view does not exist

Or in any database connection tools like Toad for Oracle.

TOAD Error ORA-00942: Table or View Does not Exist

TOAD Error ORA-00942: Table or View Does not Exist

Here we take the following steps to solve ORA-00942 in SELECT statements.

  1. Simple Test
  2. Enter Values
  3. Check Result
  4. Synonym Problem

Simple Test

You can use a simple query to test whether you have used the right way to access the table or not.

select ‘»‘ || owner || ‘».»‘ || object_name || ‘»‘ use_this from all_objects where object_type in (‘TABLE’, ‘VIEW’) and lower(owner) = lower(‘&owner’) and lower(object_name) = lower(‘&table_name’);

Enter Values

After issuing the above SQL statement, the tool you use will ask you two substitution values.

Enter owner of the table.

Enter value for owner: hr

Enter the table name.

Enter value for table_name: lottery_list

Then we’ll see the result.

Check Result

There’re only 2 possible results.

Returns Nothing

If it returns nothing or «no rows selected«, then you need to ask for the owner of the table or DBA to grant SELECT privilege to you.

GRANT SELECT ON <OWNER>.<TABLE_NAME> TO <GRANTEE>;

Returns Something

If it does return something like the following:

USE_THIS
----------------------------------------
"HR"."lottery_list"

Then you can use (copy / paste) the result in your statement.

SQL> select count(*) cnt from "HR"."lottery_list";

       CNT
----------
       107

The points to use the table correctly are:

  • Make sure the table name is correctly spelled.
  • Prefix owner’s name if the table is not yours.
  • Enclose the table name by a pair of double quotes if the identifier is case-sensitive.

Synonym Problem

If your query still failed with ORA-00942, please make sure that the table you thought is really a table or a synonym. Let’s see a case.

SQL> show user
USER is "HR"
SQL> select * from customers;
select * from customers
              *
ERROR at line 1:
ORA-00942: table or view does not exist

What message didn’t tell is the base table of the synonym. Let’s check the base table of the synonym.

SQL> select '"' || table_owner || '"."' || table_name || '"' use_this from all_synonyms where lower(synonym_name) = lower('customers');

USE_THIS
----------------------------------------
"OE"."CUSTOMERS"

The synonym could be public or private, it doesn’t matter. In either situation, you simply need the SELECT object privilege on the base table by the owner or a privileged user.

SQL> show user
USER is "SYSTEM"
SQL> grant select on "OE"."CUSTOMERS" to hr;

Grant succeeded.

We fixed the synonym problem.

ALTER TABLE

This may also apply to the following statements.

  • DROP TABLE
  • ALTER TABLE ADD COLUMN
  • ALTER TABLE ADD CONSTRAINT
  • ALTER TABLE MOVE

Now we turn to some more advanced topics.

There’re only 2 error patterns of ORA-00942 in ALTER TABLE statement.

  1. Not a Table
  2. No REFERENCES Privilege

Not a Table

Some database objects may act like tables, but they are not tables essentially. Here is a sample object named HAPPY_EMPLOYEES.

SQL> select first_name, last_name from happy_employees;

FIRST_NAME           LAST_NAME
-------------------- -------------------------
Nancy                Greenberg
Daniel               Faviet
John                 Chen
Ismael               Sciarra
Jose Manuel          Urman
Luis                 Popp

6 rows selected.

ORA-00942 when ALTER TABLE

Let’s see an example of ALTER TABLE.

SQL> alter table happy_employees move;
alter table happy_employees move
*
ERROR at line 1:
ORA-00942: table or view does not exist

The error message told us that it tried to find a table named HAPPY_EMPLOYEES, but nothing is found.

ORA-00942 when DROP TABLE

You can not even DROP TABLE.

SQL> drop table happy_employees purge;
drop table happy_employees purge
           *
ERROR at line 1:
ORA-00942: table or view does not exist

Has the table been removed before our actions? As a matter of fact, the object is not a table, even though it looks like a table. That’s why SQL parser flagged its non-existence problem.

Solutions to ORA-00942

Now, we have to know what the object type it is. A dictionary view USER_OBJECTS can be helpful.

SQL> select object_type from user_objects where upper(object_name) = upper('happy_employees');

OBJECT_TYPE
-------------------
VIEW

As a result, it’s a VIEW. Now the question is: What is the base table? How can we find it? Actually, we can learn the fact by querying USER_VIEWS:

SQL> select text from user_views where upper(view_name) = upper('happy_employees');

TEXT
--------------------------------------------------------------------------------
select first_name, last_name from employees where department_id = 100

Not only views, but synonyms are also schema objects based on tables. That is to say, no matter what you are trying to do is ALTER TABLE or DROP TABLE, you should do it on their base tables in case of ORA-00942.

No REFERENCES Privilege

If your constraint needs to reference a table owned by others, you should get an object privilege called REFERENCES on the table. For example:

SQL> conn sh/sh
Connected.
SQL> create table temp (id number, e_id number, text varchar2(30));

Table created.

SQL> alter table temp add constraint fk_eid foreign key (e_id) references hr.employees (employee_id);
alter table temp add constraint fk_eid foreign key (e_id) references hr.employees (employee_id)
                                                                        *
ERROR at line 1:
ORA-00942: table or view does not exist

Solutions to ORA-00942

To resolve ORA-00942 in such situation, we should grant REFERENCES on the table to grantee like this:

SQL> conn hr/hr;
Connected.
SQL> grant references on hr.employees to sh;

Grant succeeded.

Let’s try to add the foreign key again.

SQL> conn sh/sh
Connected.
SQL> alter table temp add constraint fk_eid foreign key (e_id) references hr.employees (employee_id);

Table altered.

As we can see, a reference constraint that points to another user’s table was added.

SELECT vs REFERENCES

Now it’s time to know some points on the differences between SELECT privilege and REFERENCES privilege.

  • SELECT privilege is not the right choice to solve ORA-00942 in such error pattern. As a result of only SELECT privilege presents, you will get ORA-01031 instead of ORA-00942 in this case.
  • For convenience, you can grant SELECT object privilege to a role, but you cannot grant REFERENCES to a role, which will fail with ORA-01931.
  • There is NO such system privilege called REFERENCE ANY TABLE just like SELECT ANY TABLE available to DBA to grant to. No, not such thing.

Понравилась статья? Поделить с друзьями:
  • Как найти образующую целиндра
  • Как найти нитраты в овощах
  • Как найти кто украл собаку
  • Как найти площадь треугольника достраивать
  • Как решать примеры найдите значение выражения при