Перейти к содержимому

Ключевое слово from не найдено там где оно ожидалось

  • автор:

Ключевое слово from не найдено там где оно ожидалось

oracle tutorial webinars

ORA-00923 is a commonly seen error that is easily resolved by simply correcting its syntax. Keep in mind ORA-00923 does not occur in Oracle 10g.

The Problem

When you are faced with this error, you will see the following message:

ORA-00923 FROM keyword not found where expected

ORA-00923 occurs when you try to execute a SELECT or REVOKE statement without a FROM keyword in its correct form and place. If you are seeing this error, the keyword FROM is spelled incorrectly, misplaced, or altogether missing. In Oracle, the keyword FROM must follow the last selected item in a SELECT statement or in the case of a REVOKE statement, the privileges. If the FROM keyword is missing or otherwise incorrect, you will see ORA-00923.

The Solution

To resolve ORA-00923, the user should make sure three possible causes are corrected. First, the user must correct the syntax. Make sure you have placed the keyword FROM in its correct place, and that no spelling errors have occurred. Secondly, if you used quotation marks in an alias, make sure that they have properly enclosed the alias and that they are double quotation marks. Lastly, make sure no reserved words were used as an alias. See the Oracle appendix for reserved words to view a complete list. For practical application of these practices on how to resolve ORA-00923, see the following examples.

In the following example, the query is missing the keyword FROM:

To correct the statement, insert the FROM keyword in the correct place, and run again:

Another example of the ORA-00923 error is when quotation marks do not properly enclose the alias, as in the following:

SELECT manager AS manager column

The alias—in this example, manager column—is not enclosed in double quotation marks. Resolve ORA-00923 by fixing this syntax mistake.

SELECT manager AS “manager column”

Looking Forward

Avoiding ORA-00923 in the future is a matter of keeping to the proper syntax when executing SELECT or REVOKE statements. While correcting this error is not difficult, simply remember the following rules to avoid seeing this error.

  1. The FROM keyword should follow the last selected item. Make sure it is not misspelled, misplaced, or missing.
  2. Make sure you have enclosed the alias in double quotation marks.
  3. Make sure no Oracle reserved word was used as an alias.

If you continue to experience this error, you may consider contacting your database administrator or a licensed Oracle consultant. Always check your consultant’s credentials and experience to ensure they meet your needs.

Ключевое слово from не найдено там где оно ожидалось

Почему я получаю эту ошибку: «ORA-00923: ключевое слово FROM не найдено там, где ожидалось»

Таким образом, у меня есть эта таблица, каждая колонна ‘A, B, C’ представляющая сторона треугольника соответственно.

Я хочу проверить, соответствует ли значение A = B, и если да, отобразить на экране «Равнобедренный».

Я не могу за жизнь меня неимую снимать эту проблему. Вот мой простой запрос:

Похоже, синтаксис в порядке, а псевдоним заключен в одинарные кавычки. Может ли кто-нибудь взглянуть и сказать мне, что случилось?

3 ответа

Похоже, синтаксис в порядке, а псевдоним заключен в одинарные кавычки. Может ли кто-нибудь взглянуть и сказать мне, что случилось?

Одиночные кавычки — это как раз то, что не так. Когда вы задаете псевдоним для чего-либо, вам нужно использовать те же правила, которые вы используете при именовании объектов и столбцов, без кавычек, чтобы Oracle рассматривал это как верхний регистр по умолчанию, или использовать двойные кавычки, чтобы вы могли решить сами. Всегда нужно тщательно продумывать все, что чувствительно к регистру, это требует больших усилий, и о нем часто забывают. Вы же не хотите тратить часы на чесание в затылке, говоря: «Это должно быть здесь».

Изменить — после пересмотра того, что вы действительно могли бы получить после: Кроме того, вы не можете просто присвоить каждому столбцу одно целое, это странно. Вы могли иметь в виду дополнительную строку вроде

Да не совсем; если я вас правильно понял, вы должны использовать CASE (строки 1–6 представляют собой образцы данных; они у вас уже есть, поэтому нужный вам запрос начинается со строки № 7):

Почему я получаю сообщение «ORA-00923: ключевое слово FROM не найдено там, где ожидалось»?

Мне пришлось заменить двойные кавычки на одинарные в запросе, чтобы получить строку запроса для компиляции в среде IDE при переносе с Delphi на C#.

IOW с таким SQL, который работает в Delphi и Toad:

. Мне пришлось изменить его на это, чтобы он скомпилировался в Visual Studio:

Однако SQL не будет работать таким образом — я получаю сообщение об ошибке «ORA-00923: ключевое слово FROM не найдено там, где ожидалось» (как в Toad, так и при попытке выполнить SQL в приложении C#).

Как я могу заставить его скомпилировать и запустить?

B. Clay Shannon-B. Crow Raven

мы можем увидеть строку с размещением «от»? — KevinDTimm

Я могу избежать проблемы, удалив псевдонимы столбцов, которые в данном случае мне не нужны, но что, если я это сделаю/когда это сделает кто-то другой? — B. Clay Shannon-B. Crow Raven

@Кевин: . . . W.INTERLOPERTYPE, W.OFFICEDIVISION FROM RTINTERLOPERSTAT R, ABCWORKER W — B. Clay Shannon-B. Crow Raven

Что это @» префикс? Это точно недопустимый SQL. — a_horse_with_no_name

Нет, это для C#, чтобы я мог распределить строки SQL по нескольким строкам в редакторе, не работая над конкатенацией строк. IOW, то, что я только что написал (выше), вызовет ошибку компиляции, если я добавлю его к: String s = «, но если добавить его к String s = @», все будет в порядке. — B. Clay Shannon-B. Crow Raven

2 ответы

Кавычки вокруг псевдонимов вашей колонки вызывают изжогу.

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

Во втором случае Oracle интерпретирует псевдонимы столбцов в одинарных кавычках как строки, что его искажает.

В Oracle вам тоже не нужно: вы должны иметь возможность просто кодировать:

или, используя необязательный AS ключевое слово:

Надеюсь это поможет.

ответ дан 19 апр.

Обычно это не работает, если у вас есть встроенные комментарии в запросе.

Не тот ответ, который вы ищете? Просмотрите другие вопросы с метками sql oracle ora-00923 or задайте свой вопрос.

Динамическая вставка — ORA-00923: ключевое слово FROM не найдено там, где ожидалось

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

Однако я продолжаю получать сообщение об ОШИБКЕ-ORA-00923: ключевое слово FROM не найдено там, где ожидалось. Любая помощь приветствуется.

Формы c голосовым вводом в React с помощью Speechly

Flatpickr: простой модуль календаря для вашего приложения на React

Что такое cURL в PHP? Встроенные функции и пример GET запроса

Ответы 4

Вам нужно заключать в одинарные кавычки ваши литеральные строковые значения, а одинарные кавычки, используемые для содержания динамической строки SQL, не учитываются. Мы можем попробовать использовать две одинарные кавычки для представления одной буквальной одинарной кавычки:

Обратите внимание, что в подзапросе вы сравниваете pField , текстовую переменную, с 0 без кавычек, то есть с целым числом. Это не имеет смысла, поэтому в приведенном выше фрагменте я сравниваю с ‘0’ вместо числа.

pField относится к числовому полю pTable

Ну, ваша сигнатура функции показывает, что pField — это VARCHAR2 , а не число. Итак, мой ответ не изменится, если ваша функция также не изменится.

pField — это VARCHAR2, поскольку оно относится к имени (а не к типу) данного столбца pTable. Ссылочное поле является числовым; отсюда и сравнение с 0.

Ваше объяснение не очень понятно, я пытаюсь прояснить, что я понял (напрягая воображение) из этого, с помощью следующего примера/дальнейшего описания

Допустим, у вас есть две основные таблицы

Если вы передаете tbl_1, value_1 в качестве параметров вашей процедуры, ваш вставляемый SQL должен быть

Когда вы передаете tbl_2, value_2 в качестве параметров вашей процедуры, ваш вставляемый SQL должен быть

Если это понимание правильное, то должно работать следующее

Примечание Я оставил вам обработку транзакций и исключений в качестве упражнения. Также обратите внимание, что на момент написания этого у меня не было доступа к Oracle DB, поэтому я не мог создать/скомпилировать, чтобы отсеять любую ошибку/проблему. Вы должны попытаться исправить проблемы (если они есть). Если вы не можете оставить комментарий, я сделаю это, когда у меня будет доступ к экземпляру БД.

Oracle / PLSQL: ORA-00923 Error Message

Learn the cause and how to resolve the ORA-00923 error message in Oracle.

Description

When you encounter an ORA-00923 error, the following error message will appear:

  • ORA-00923: FROM keyword not found where expected

Cause

You tried to execute a SELECT statement, and you either missed or misplaced the FROM keyword.

Resolution

The option(s) to resolve this Oracle error are:

Option #1

This error can occur when executing a SELECT statement that is missing the FROM keyword.

For example, if you tried to execute the following SELECT statement:

You could correct this SELECT statement by including the FROM keyword as follows:

Option #2

This error can also occur if you use an alias, but do not include the alias in double quotation marks.

For example, if you tried to execute the following SQL statement:

You could correct this SELECT statement by using double quotation marks around the alias:

Option #3

This error can also occur if you add a calculated column to a SELECT * statement.

For example, if you tried to execute the following SQL statement:

You could correct this SELECT statement by including the table name qualifier in front of the wildcard:

Option #4

You can also generate this error by having an unbalanced set of parenthesis.

For example, if you tried to execute the following SQL statement:

You could correct this SELECT statement by removing the extra closing parenthesis just prior to the alias:

ORA-00923: FROM keyword not found where expected

The ORA-00923: FROM keyword not found where expected error occurs when the FROM keyword is missing, misspelled, or misplaced in the Oracle SQL statement such as select or delete. The FROM keyword is used to identify the table name. If an error occurs when checking for the FROM keyword, the table name cannot be found. If the the FROM keyword is missing from the SQL query, misspelled, or misplaced in the select statement, Oracle parser will fail to detect the FROM keyword. If the FROM keyword is not found where it should be, an error message ORA-00923: FROM keyword not found where expected will be displayed.

The FROM keyword is used in the select statement to specify the table or view name. The select statement could not identify the table names if the FROM keyword was missing, misspelled, or misplaced. The issue is caused by the FROM keyword or the code written before the FROM keyword. The issue ORA-00923: FROM keyword not found where expected will be fixed if you rewrite the select query along with the FROM keyword.

When this ORA-00923 error occurs

The error will occur in the Oracle database if the FROM keyword is missing, misspelled, or misplaced in the select statement. The error will occur if there are any errors in the code written before the FROM keyword. If you examine the sql query in and around the FROM keyword, you may be able to rectify the error.

Root Cause

The FROM keyword will be used in the select statement to specify the table or view name from which the data will be retrieved. If the FROM keyword is missing, misplaced, or misspelled in the select statement, the table name cannot be identified. In this example, the select statement expects the presence of a FROM keyword in the query. As a result, an Oracle error “ORA-00923: FROM keyword not found where expected” will be thrown.

Solution 1

If the FROM keyword is not present in the select statement, it should be added before the table or view name. The select statement reads the table or view name and retrieves data from it. Check that the FROM keyword is present in the select query.

Problem
Solution

Solution 2

Oracle will give an error if the FROM keyword in the select statement is misspelled. The FROM keyword was not found in the query, thus the select statement failed. In this scenario, the table or view name could not be discovered. The FROM keyword must be properly written. The FROM keyword is case insensitive.

Problem
Solution

Solution 3

If the FROM keyword is misplaced in the select statement, an error notice will be produced. The FROM keyword should come before the table or view name and after the list of column names. If the FROM keyword is used in combination with the name of a column, Oracle will consider the FROM keyword to be one of the columns and will expect the FROM keyword to identify the table or view name.

Problem
Solution

Solution 4

If there is a mistake in the list of column names in the select statement, an error message will be displayed. Oracle will treat the error in the column list and expects the FROM keyword in the select statement to specify the table or view name. The column name contains a space in between and no double quotes is used to the column name.

Problem
Solution

Solution 5

The error will be thrown if the column name is identified with a single quotation. The column name should be included in double quotation marks. The issue may be fixed by changing the single quotation to a double quotation. In Oracle, a single quote will be used to identify the string value or date value. In the column names, a double quotation should be utilized.

Problem
Solution

Solution 6

The from keyword error happens in the Oracle database if any of the oracle keywords is used as the column names in the select statement. The keyword should not be used as the name of a column. The issue may be fixed by deleting the keyword from the column name.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *