Oracle в этом предложении select ожидается фраза into
Добрый день!
Написал вот такую программку на MS SQL:
и пытаюсь то же самое сделать на Oracle SQL Developer:
но как только я пишу что-то после end loop (например, строку, которая у меня закомментирована) у меня ошибка: "В этом предложении Select ожидается фраза INTO"
Что я делаю неправильно? Точнее, что я не делаю, чтобы все заработало?
Александр.
Ожидается ли что-то на смену SQL?
Дейт пишет в книге от 2008 года: Забавно, что Дейт язык SQL обвиняет в нереляционности. А.
Дана фраза, в которой слова разделены одним пробелом, а сама фраза заканчивается точкой
Дана фраза, в которой слова разделены одним пробелом, а сама фраза заканчивается.
Дана фраза. Проверить, является ли она палиндромом. Фраза может содержать знаки препинания и символы пробела
Помогите пожалуйста. Дана фраза. Проверить, является ли она палиндромом. Фраза может содержать.
Потому что в PL/SQL нет просто SELECT. Либо запрос возвращает одну строку, тогда форма SELECT . INTO (она у тебя выше присутствует). Либо запрос возвращает несколько строк, тогда это делается через курсор. Если через курсор, тогда, если ты хочешь увидеть строки на экране, нужно предпринять еще доп. усилия для вывода на экран (например, с пом. dbms_output.put_line).
Спасибо! Изучаю dbms_output.put_line и cursor.
Извините, но я еще не все понимаю. А нельзя ли поподробнее? И было бы вообще классно, если бы Вы написали, как должна выглядеть на Oracle SQL программа, написанная мною на MS SQL.
Александр.
Еще раз спасибо! И еще прошу чуть-чуть помощи.
Table TEMP created.
PL/SQL procedure successfully completed.
но больше ничего. а где выводимые значения?
Александр.
Добавлено через 6 минут
. продолжение предыдущего письма.
Смысл программы в следующем.
Есть таблица, два поля - название и количество (например, название отдела и количество сотрудников)
в результате я хочу получить таблицу, содержащую по каждому отделу столько записей, сколько в ней сотрудников.
Как бы операция обратная COUNT(*).
Александр.
Best Answer
SQL Developer is not your database, it's the interface you use to interact with the database. To find your Oracle db version, run
To your question: If you want to run a SELECT statement to retrieve information from your tables, just run the SELECT statement directly - don't enclose it within a PL/SQL program unit (an "anonymous block" in your case - the structure with a DECLARE section and BEGIN and END markers).
It seems you want to run a query where you give the start date and the end date as parameters. The way to do that is to include BIND VARIABLES in your query (variable names are preceded by colon : ) You can declare the variables and give them values in a PL/SQL block before running the SELECT query.
Something like this:
Note that when you declare the variable (with the VARIABLE command) you are not using the colon before the variable name. You do use the colon everywhere else.
Can you adapt this to your example? Give it a try! Note: This is how it works in SQL*Plus; in SQL Developer you can just enter the SELECT statement, with the bind variables; when you execute it, SQL Developer will ask you for values for the bind variable(s). Also, while some systems support the DATE data type for bind variables, others don't; SQL*Plus doesn't, so I used VARCHAR2 and converted to a date in the query itself.
EDIT: I didn't explain the error message. In PL/SQL you can't run standard (SQL) SELECT statements. You can run SELECT statements that return values to PL/SQL variables (either scalar variables or collections, such as arrays of records, etc.) If you have a SELECT statement in a PL/SQL block, you must specify the variable(s) INTO which the values are to be returned. By the look of your code, I assumed you weren't trying to write PL/SQL code that does something, but instead you just wanted to run a SELECT statement that returns results depending on two runtime variables used in the WHERE clause. If I guessed wrong, say so.
Как я могу сделать то же самое в Oracle? В настоящее время я пытаюсь сделать следующее:
почему это не работающего?
убедитесь, что запрос возвращает только одну строку:
по умолчанию инструкция SELECT INTO должна возвращать только одну строку. В противном случае PL/SQL вызывает предопределенное исключение TOO_MANY_ROWS, а значения переменных в предложении INTO не определены. Убедитесь, что ваше предложение WHERE достаточно специфично, чтобы соответствовать только одной строке
Если строки не возвращаются, PL / SQL вызывает NO_DATA_FOUND. Вы можете охранять против этого исключения, выбрав результат агрегатной функции, такой как COUNT(*) или AVG (), где это практично. Эти функции гарантированно возвращают одно значение, даже если строки не соответствуют условию.
A ВЫБРАТЬ . Оператор BULK COLLECT INTO может возвращать несколько строк. Для хранения результатов необходимо настроить переменные коллекции. Можно объявить ассоциативные массивы или вложенные таблицы, которые растут по мере необходимости для хранения всего результирующего набора.
неявное курсор SQL и его атрибуты %NOTFOUND, %FOUND, %ROWCOUNT и %ISOPEN предоставляют сведения о выполнении инструкции SELECT INTO.
не совсем уверен, что вы после, но в PL / SQL вы просто
один дополнительный пункт:
при конвертации из tsql to plsql вы должны беспокоиться о no_data_found исключение
на tsql если no data found тогда переменная будет null а не exception
ORA-01422: точная выборка возвращает больше запрошенного количества строк
Если вы не укажете точную запись, используя условие where, вы получите вышеуказанное исключение
для хранения вывода одной строки в переменную из запроса select into:
объявить v_username varchare(20); Выберите имя пользователя в v_username от пользователей, где user_id = '7';
это сохранит значение одной записи в переменной v_username.
для хранения нескольких строк, выводимых в переменную из запроса select into:
вы должны использовать функцию listagg. listagg объединяет результирующие строки a столб в один столб, а также, чтобы различать их, вы можете использовать специальный символ. использовать запрос, как показано ниже Выберите listagg (username || ',' ) в группе (order by username) в v_username от пользователей;
Решение
Во-первых, в SQL Dev, насколько мне помнится, данные выводятся на отдельной вкладке, название которой что-то типа Output, а не на вкладке с текстом процедуры.
Во-вторых, должен быть включен вывод на экран (где включается не помню, что-то типа SERVEROUTPUT). По идее он д.б. включен по умолчанию, но не мешает проверить. В крайнем случае можно первой командой после BEGIN выдать dbms_output.enable;
Большущее спасибо! Узнал много нового.
И уж совсем, если обнаглеть. Как подчистить за собой? Удалить таблицу Temp? Чтобы сразу и результат получить, и таблицы Temp не было. Я это делаю в два действия, а хотелось бы в одно.
Александр.
Если это обычная таблица, то кроме как с пом. DROP никак. Однако если ты работал с MS SQL, подозреваю, что ты создаешь временную таблицу в их стиле.
В Oracle все по другому. Временная таблица создается командой
В результате в словаре создается описание таблицы. Если ты что-то с ней делаешь, то это происходит в памяти твоего процесса, остальным не видно. В зависимости от опций создания таблицы данные в ней хранятся либо до COMMIT/ROLLBACK, либо до конца твоей сессии. Таким образом в большинстве случаев ни чистить, ни удалять ее не нужно,
а в следующий раз таблицу можно не создавать, а использовать описание уже имеющейся.
While executing the stored procedure I am getting following error.
Can you please provide me the resolution for this issue.while executing the same command in sql it is working fine but in stored procedure compilation error is occurring it means in stored procedure INTO replacing AS will give the same output please clarify.
2 Answers 2
The error message is fairly self-explanatory; the PL/SQL version of a SELECT requires an INTO clause so the result of your query has somewhere to go. You already have an OUT parameter to put the value into:
The SELECT is now INTO your OUT parameter, and its value will be available to whoever calls your procedure.
This only works if your query will always return exactly one row. If it doesn't return anything then you'll get a no-data-found exception; if it returns more than one row you'll get a too-many-rows exception. And you need to have a variable for each column your query returns - only one in this case. You can also declare a local variable (between IS and BEGIN ) to hold temporary values that you will manipulate within the procedure, but you don't need that here either.
When you compiled your procedure it would have said it compiled with warnings, because of that syntax error. If you created it in SQL*Plus or SQL Developer, and maybe some other tools, you could have seen the error straight away by issuing the command show errors , or at any time by querying the user_errors view. When you called the procedure it was invalid and was automatically recompiled, which just regenerated the same error as nothing had changed; that's when you saw the PLS-00428 message. It's better to look for errors at compile time than wait for recompilation at execution time.
Incidentally, it's generally better to convert a fixed value into the data type used by your table, rather than the other way round. When you do this:
. every column in your table has to have its msg_when_created DATE value converted to a string to be compared to the in_start_date string, which would prevent an index on that column being used. It's preferable to do:
or if your column has a time component:
It would be even better to make your caller convert the value to a DATE so you don't have to worry about matching a passed format:
The SELECT INTO statement retrieves values from one or more database tables (as the SQL SELECT statement does) and stores them in variables (which the SQL SELECT statement does not do).
The SELECT INTO statement with the BULK COLLECT clause is vulnerable to aliasing, which can cause unexpected results. For details, see "SELECT BULK COLLECT INTO Statements and Aliasing" .
Oracle Database SQL Language Reference for the syntax of the SQL SELECT statement
Specify DISTINCT or UNIQUE if you want the database to return only one copy of each set of duplicate rows selected. These two keywords are synonymous. Duplicate rows are those with matching values for each expression in the select list.
Restrictions on DISTINCT and UNIQUE Queries
The total number of bytes in all select list expressions is limited to the size of a data block minus some overhead. This size is specified by the initialization parameter DB_BLOCK_SIZE .
You cannot specify DISTINCT if the select_list contains LOB columns.
(Default) Causes the database to return all rows selected, including all copies of duplicates.
If the SELECT INTO statement returns no rows, PL/SQL raises the predefined exception NO_DATA_FOUND . To guard against this exception, select the result of the aggregate function COUNT(*) , which returns a single value even if no rows match the condition.
With this clause, the SELECT INTO statement retrieves one or more columns from a single row and stores them in either one or more scalar variables or one record variable. For more information, see "into_clause ::=" .
With this clause, the SELECT INTO statement retrieves an entire result set and stores it in one or more collection variables. For more information, see "bulk_collect_into_clause ::=" .
Anything that can follow the keyword FROM in a SQL SELECT statement, described in Oracle Database SQL Language Reference .
Example 2-25, "Assigning Value to Variable with SELECT INTO Statement"
Example 5-50, "SELECT INTO Assigns Values to Record Variable"
Example 6-38, "SAVEPOINT and ROLLBACK Statements"
Example 6-43, "Declaring Autonomous Function in Package"
Example 7-20, "Validation Checks Guarding Against SQL Injection"
Example 12-16, "Bulk-Selecting Two Database Columns into Two Nested Tables"
Example 12-17, "Bulk-Selecting into Nested Table of Records"
Example 12-21, "Limiting Bulk Selection with ROWNUM, SAMPLE, and FETCH FIRST"
I have been a SQL Server developer for couple decades and recently started working on Oracle PL SQL. I have a simple query with a simple question. Maybe you can explain to me why I got that error, so I will understand the concept.Thanks.
declare p_start_dt date := '01-Jun-20';
p_end_dt date := '30-Jun-20';
and date2 >= p_end_dt;
Читайте также: