Меню

Ora 00907 missing right parenthesis ошибка

I have been looking at this code for the past two days now and I can not seem to get it to work. It keeps giving me

ORA-00907: missing right parenthesis.

I know that this is a topic that comes up a lot but for some reason none of the examples I have seen has helped me. Can someone please tell me why I got this error and how do I fix it? I am pretty sure that it has nothing to do with my parenthesis, maybe it’s my CONSTRAINTS?

DROP TABLE T_customers CASCADE CONSTRAINTS;
DROP TABLE dvd_collection CASCADE CONSTRAINTS;
DROP TABLE vhs_collection CASCADE CONSTRAINTS;

CREATE TABLE T_customers   (


                           customer_id         VARCHAR2 (8) PRIMARY KEY,
                           last_name           VARCHAR2 (30) NOT NULL,
                           first_name          VARCHAR2 (20) NOT NULL,
                           street             VARCHAR2 (30) NOT NULL,
                           city               VARCHAR2 (30) NOT NULL,
                           state                 CHAR (2) NOT NULL,
                                    CHECK (state IN ('GA','DC','VA','NY')),
                           zip_code           CHAR (5)
                                    CHECK (TO_NUMBER(zip_code)
                              BETWEEN 10000 AND 27999),
                           home_phone         VARCHAR2 (12) UNIQUE,
                           work_phone         VARCHAR2 (12) UNIQUE,
                           email                 VARCHAR2 (95) NOT NULL);




CREATE TABLE historys_T    (

          history_record       VARCHAR2 (8),
          customer_id       VARCHAR2 (8), 
          CONSTRAINT historys_T_FK FOREIGN KEY (customer_id) REFERENCES T_customer
                                       ON DELETE CASCADE,
                           order_id           VARCHAR2 (10) NOT NULL,
                                 CONSTRAINT fk_order_id_orders  
                                       REFERENCES orders
                                       ON DELETE CASCADE);


CREATE TABLE orders     (

                           order_id           VARCHAR2 (10) PRIMARY KEY,
                           m_p_unique_id       VARCHAR2 (10),
                                    CONSTRAINT orders_FK FOREIGN KEY (m_p_unique_id) REFERENCES library (m_p_unique_id)
                           order_date          DATE DEFAULT);



CREATE TABLE library_T     (

                           m_p_unique_id       VARCHAR2 (10)  PRIMARY KEY,
                           movie_title         VARCHAR2 (80)  NOT NULL,
                           serial_number       VARCHAR2 (10)  NOT NULL,
                           movie_id_number   VARCHAR2 (10)  NOT NULL,
                           movie_cast        VARCHAR2 (100) NOT NULL,
                           movie_format    CHAR (3) NOT NULL, 
                                  CONSTRAINT library_FK REFERENCES formats (movie_format));

CREATE TABLE formats_T     (

                           movie_format      CHAR (3) PRIMARY KEY,
                           movie_title       VARCHAR2 (80) NOT NULL,
                           m_p_unique_id     VARCHAR2 (10) NOT NULL,
                                 CONSTRAINT format_FK  REFERENCES library (m_p_unique_id));



CREATE TABLE dvd_collection (      


                           m_p_unique_id       VARCHAR2 (10) NOT NULL,
                           serial_number       VARCHAR2 (10) NOT NULL,
                           movie_id_number  VARCHAR2 (10) NOT NULL,
                           movie_title         VARCHAR2 (80) NOT NULL,
                           movie_cast          VARCHAR2 (100) NOT NULL,
                           movie_format     VARCHAR2 (80) NOT NULL,
                           movie_rating    VARCHAR2 (6) NOT NULL,
                           movie_distributer    VARCHAR2 (30) NOT NULL,
                           movie_price         NUMBER (3,2) NOT NULL,
                           movie_length     NUMBER (3) NOT NULL,
                           movie_award         VARCHAR2 (175) NOT NULL,
                           movie_release       DATE); 


CREATE TABLE vhs_collection            
(

                           m_p_unique_id       VARCHAR2 (10)NOT NULL,
                           serial_number       VARCHAR2 (10) NOT NULL,
                           movie_id_number  VARCHAR2 (10) NOT NULL,
                           movie_title         VARCHAR2 (80) NOT NULL,
                           movie_cast        VARCHAR2 (100) NOT NULL,
                           movie_format    VARCHAR2 (80) NOT NULL,
                           movie_rating    VARCHAR2 (6) NOT NULL,
                           movie_distributer    VARCHAR2 (30) NOT NULL,
                           movie_price         NUMBER (3,2) NOT NULL,
                           movie_length     NUMBER (3) NOT NULL,
                           movie_award         VARCHAR2 (175) NOT NULL,
                           movie_release        DATE);

Here are the results I get when I run the code:

Table dropped.

Table dropped.

Table dropped.

Table created.

                                       ON DELETE CASCADE)
                                       *

ERROR at line 10:
ORA-00907: missing right parenthesis

                           order_date          DATE DEFAULT)
                           *

ERROR at line 6:
ORA-00907: missing right parenthesis

                                  CONSTRAINT library_FK REFERENCES formats (movie_format))
                                                                           *

ERROR at line 9:
ORA-00907: missing right parenthesis

                                 CONSTRAINT format_FK  REFERENCES library (m_p_unique_id))
                                                                          *

ERROR at line 6:
ORA-00907: missing right parenthesis
Table created.

Table created.               

ORA-00907: missing right parenthesis error occurs when a left parenthesis is used without a right parenthesis to close it in SQL statements such as create table, insert, select, subquery, and IN clause. The right parenthesis is missing. All parentheses must be used in pairs. SQL statements that include multiple items should be contained in parentheses. The error ORA-00907: missing right parenthesis will be thrown If the left parenthesis has been used in the SQL Statement but the right parenthesis is missing.

Oracle’s collection of items is denoted by a parenthesis. If the right parenthesis is missing, Oracle will be unable to recognise the items specified after that. The error message ORA-00907: missing right parenthesis will be shown. The right parenthesis indicates the closing of the item list. Oracle could not recognise the end of the items list if the right parenthesis was missing. All left parenthesis in Oracle SQL must be paired with a right parenthesis. You’ll receive this error ORA-00907: missing right parenthesis if there are more left parenthesis than right parentheses.

When the ORA-00906 error occurs

The collection of items could not be provided if the right parenthesis was missing in the SQL Statement such as create table, insert table, select subquery, and IN clause. Create a SQL query that should include a collection of items but does not include the right parenthesis. In this case, the error message will be displayed. The error will be resolved if the right parenthesis is added before the collection of items

Problem

create table dept(
id number primary key,
name varchar2(100)

Error

Error starting at line : 3 in command -
create table dept(
id number primary key,
name varchar2(100)
Error report -
ORA-00907: missing right parenthesis
00907. 00000 -  "missing right parenthesis"

Root Cause

In Oracle, the collection of items is defined using enclosed parentheses. Oracle could not identify the closing of the collection of items list if the right parenthesis was missing. Oracle anticipates the right parenthesis after the list. Oracle will give an error if the right parenthesis is missing.

Solution 1

If the parenthesis in the anticipated SQL Statement is missing, the error will be thrown. The right parenthesis for specifying the item collection is missing. The error will be fixed if you add the missing right parentheses.

Problem

create table dept(
id number primary key,
name varchar2(100)

Error report -
ORA-00907: missing right parenthesis
00907. 00000 -  "missing right parenthesis"

Solution

create table dept(
id number primary key,
name varchar2(100)
);

Solution 2

The column data type, as well as the size or precision of the data type, should be provided. The error will be thrown if the size of the data type is provided in the column definition without right parenthesis. Oracle will look for the size by enclosing a value in parentheses. The error message will be displayed if the right parenthesis is missing right after the data type size.

Problem

create table dept(
id number primary key,
name varchar2(100,
sal number
);

ORA-00907: missing right parenthesis
00907. 00000 -  "missing right parenthesis"

Solution

create table dept(
id number primary key,
name varchar2(100),
sal number
);

Solution 3

The subqueries are added with a enclosed parenthesis in the where clause. If the right parenthesis is missing in the subquery, the error message will be shown.

Problem

select * from employee where deptid in (select id from dept ;

ORA-00907: missing right parenthesis
00907. 00000 -  "missing right parenthesis"

Solution

select * from employee where deptid in (select id from dept) ;

Solution 4

The values in the IN clause. is enclosed with parenthesis. If the right parenthesis is missing, the closing of the list could not be identified. The error message will be shown.

Problem

select * from employee where deptid in (1,2 ;

ORA-00907: missing right parenthesis
00907. 00000 -  "missing right parenthesis"

Solution

select * from employee where deptid in (1,2) ;

Solution 5

All left parenthesis in Oracle SQL must be paired with a right parenthesis. You’ll see this error ORA-00907: missing right parenthesis if there are more left parenthesis than right parentheses.

Problem

select * from employee where deptid in (select id from dept where name in (select name from branches) ;

ORA-00907: missing right parenthesis
00907. 00000 -  "missing right parenthesis"

Solution

select * from employee where deptid in (select id from dept where name in (select name from branches)) ;

I’ve written a query to test out a simple linear regression to get the line of best-fit between two sets of weight measures. It should hopefully return results like below, but it’s throwing a strange error

‘ORA-00907 Missing Right Parenthesis’

and TOAD is pointing towards the part where it says:

case ( when trn.wid_location = 28.3 then 

I’ve been combing it over for missing parenthesis but I don’t think that’s the issue because if I replace the case statement with

100 as mine,

the error disappears and the query executes.

Any thoughts?

Cheers,

Tommy

select
      decode(wid_location,28.3,'CL',29.6,'DA') as site,
      (n*sum_xy - sum_x*sum_y)/(n*sum_x_sq - sum_x*sum_x) as m,
      (sum_y - ((n*sum_xy - sum_x*sum_y)/(n*sum_x_sq - sum_x*sum_x))*sum_x)/n as b 

from (
        select 
               wid_location,
               sum(wids) as sum_x,
               sum(mine) as sum_y,
               sum(wids*mine) as sum_xy,
               sum(wids*wids) as sum_x_sq,
               count(*) as n

        from (                                                                        
                select 
                       trn.wid_location,
                       con.empty_weight_total as wids,                                                                    
                       case ( 
                              when trn.wid_location = 28.3 then con.empty_weight_total*0.900-1.0
                              when trn.wid_location = 29.6 then con.empty_weight_total*0.950-1.5
                              end                
                            ) as mine   

                from widsys.train trn
                     inner join widsys.consist con
                     using (train_record_id)

                where mine_code = 'YA'
                      and to_char(trn.wid_date,'IYYY') = 2009
                      and to_char(trn.wid_date,'IW') = 29

                                 )

        group by wid_location
     )

And here are the results i’d be happy to see

--    +----------+--------+----------+
--    | SITE     | M      | B        |
--    +----------+--------+----------+
--    | CL       | 0.900  | -1.0     |
--    +----------+--------+----------+
--    | DA       | 0.950  | -1.5     |
--    +----------+--------+----------+

I’ve written a query to test out a simple linear regression to get the line of best-fit between two sets of weight measures. It should hopefully return results like below, but it’s throwing a strange error

‘ORA-00907 Missing Right Parenthesis’

and TOAD is pointing towards the part where it says:

case ( when trn.wid_location = 28.3 then 

I’ve been combing it over for missing parenthesis but I don’t think that’s the issue because if I replace the case statement with

100 as mine,

the error disappears and the query executes.

Any thoughts?

Cheers,

Tommy

select
      decode(wid_location,28.3,'CL',29.6,'DA') as site,
      (n*sum_xy - sum_x*sum_y)/(n*sum_x_sq - sum_x*sum_x) as m,
      (sum_y - ((n*sum_xy - sum_x*sum_y)/(n*sum_x_sq - sum_x*sum_x))*sum_x)/n as b 

from (
        select 
               wid_location,
               sum(wids) as sum_x,
               sum(mine) as sum_y,
               sum(wids*mine) as sum_xy,
               sum(wids*wids) as sum_x_sq,
               count(*) as n

        from (                                                                        
                select 
                       trn.wid_location,
                       con.empty_weight_total as wids,                                                                    
                       case ( 
                              when trn.wid_location = 28.3 then con.empty_weight_total*0.900-1.0
                              when trn.wid_location = 29.6 then con.empty_weight_total*0.950-1.5
                              end                
                            ) as mine   

                from widsys.train trn
                     inner join widsys.consist con
                     using (train_record_id)

                where mine_code = 'YA'
                      and to_char(trn.wid_date,'IYYY') = 2009
                      and to_char(trn.wid_date,'IW') = 29

                                 )

        group by wid_location
     )

And here are the results i’d be happy to see

--    +----------+--------+----------+
--    | SITE     | M      | B        |
--    +----------+--------+----------+
--    | CL       | 0.900  | -1.0     |
--    +----------+--------+----------+
--    | DA       | 0.950  | -1.5     |
--    +----------+--------+----------+

Содержание

  1. ORA-00907: отсутствует правая скобка 2
  2. 4 ответы
  3. ORA-00907: отсутствует правая скобка
  4. ORA-00907: missing right parenthesis
  5. Best Answer
  6. Oracle mechanics
  7. 27.08.2009
  8. ora-904 ora-907 при использовании коррелированных подзапросов
  9. ora-904 «%s: invalid identifier»
  10. ora-907 «missing right parenthesis»
  11. ora-907
  12. Ошибка Oracle — ORA-00907: отсутствует правая скобка
  13. 2 ответы

ORA-00907: отсутствует правая скобка 2

Я пытаюсь выполнить этот запрос, чтобы получить некоторые результаты в db-visualizer, но продолжаю получать следующий ответ:

Режимы секции мощности:

[Код ошибки: 907, состояние SQL: 42000] ORA-00907: отсутствует правая скобка

отредактированный Запрос:

4 ответы

Нет необходимости в производном табличном/встроенном представлении. Но неясно, находятся ли столбцы, упорядоченные по, уже в запросе (IE: e.*), поэтому я явно добавил их в конец.

Я переписал запрос, чтобы использовать синтаксис соединения ANSI-92 — ваш запрос использует давно устаревшие средства для внешних соединений.

У меня нет вашей базы данных и таблиц. Самый простой способ определить проблему — урезать запрос до тех пор, пока он не начнет возвращать данные. Затем добавьте критерии (столбец, таблицу, предложение WHERE/и т. д.) один за другим, чтобы увидеть, где что-то идет не так.

Я получаю следующее сообщение, когда использую ваш запрос: «ORA-00933: команда SQL неправильно завершена» — Иш

Я удалил () и изменил его на substr(match_desc,1,2) = ’00’ . Но я все еще получаю ту же ошибку — Иш

я предполагаю, что ваш графический интерфейс не заменяет

правильно. попробуй это:

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

@ Я просто запускаю выбор из двойного? (т.е. не помещайте это в свой исходный sql или что-то еще . просто запустите его в одиночку. — ДаззаЛ

Проблема была в &tablename_v. необходимо было удалить, а имя таблицы (т.е. DATES) должно было быть вставлено на место. Я попробовал, и это сработало.

Но всем спасибо за помощь! Это очень ценится 🙂

Источник

ORA-00907: отсутствует правая скобка

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

ORA-00907: missing right parenthesis .

Я знаю, что эта тема возникает очень часто, но по какой-то причине ни один из примеров, которые я видел, мне не помог. Может кто-нибудь сказать мне, почему я получил эту ошибку и как ее исправить? Я почти уверен, что это не имеет ничего общего с моей круглой скобкой, может быть, это мои ОГРАНИЧЕНИЯ?

Вот результаты, которые я получаю, когда запускаю код:

ORA-00907: missing right parenthesis

Это одно из нескольких общих сообщений об ошибках, которые указывают на то, что наш код содержит одну или несколько синтаксических ошибок. Иногда это может означать, что мы буквально опустили правую скобку; это достаточно легко проверить, если мы используем редактор, который имеет возможность соответствия скобкам (большинство текстовых редакторов, предназначенных для кодеров). Но часто это означает, что компилятор обнаружил ключевое слово вне контекста. Или, возможно, это слово с ошибкой, пробел вместо подчеркивания или пропущенная запятая.

К сожалению, возможных причин, по которым наш код не компилируется, практически бесконечно, и компилятор просто недостаточно умен, чтобы различать их. Таким образом, он бросает общее, немного загадочное сообщение вроде ORA-00907: missing right parenthesis и оставляет нам, чтобы определить настоящего цветущего.

В опубликованном скрипте есть несколько синтаксических ошибок. Сначала я расскажу об ошибке, которая вызывает этот ORA-0097, но вам нужно исправить их все.

Ограничения внешнего ключа могут быть объявлены вместе со ссылочным столбцом или на уровне таблицы после того, как были объявлены все столбцы. У них разный синтаксис; ваши сценарии смешивают оба, и поэтому вы получаете ORA-00907.

Встроенное объявление не имеет запятой и не включает имя ссылочного столбца.

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

Вот список других синтаксических ошибок:

  1. Указанная таблица (и указанный первичный ключ или ограничение уникальности) должны уже существовать, прежде чем мы сможем создать для них внешний ключ. Таким образом, вы не можете создать внешний ключ HISTORYS_T до тех пор, пока не создадите указанную ORDERS таблицу.
  2. Вы неправильно написали имена таблиц, на которые есть ссылки в некоторых предложениях внешнего ключа ( LIBRARY_T и FORMAT_T ).
  3. Вам необходимо указать выражение в предложении DEFAULT. Для DATE столбцов , которые, как правило , текущая дата, DATE DEFAULT sysdate .

Хладнокровный взгляд на собственный код — это навык, который нам всем нужно приобрести, чтобы быть успешными разработчиками. Знакомство с документацией Oracle действительно помогает. Параллельное сравнение вашего кода и примеров в Справочнике SQL помогло бы вам разрешить эти синтаксические ошибки значительно менее чем за два дня. Найдите его здесь (11g) и здесь (12c) .

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

  1. Вы не назвали большинство своих ограничений. Oracle даст им имя по умолчанию, но оно будет ужасным и затруднит понимание словаря данных. Явное обозначение каждого ограничения помогает нам ориентироваться в физической базе данных. Это также приводит к более понятным сообщениям об ошибках, когда наш SQL обнаруживает нарушение ограничения.
  2. Назовите свои ограничения последовательно. HISTORY_T имеет ограничения, вызванные historys_T_FK и fk_order_id_orders , ни одно из которых не помогает. Полезное соглашение _

_fk . Так history_customer_fk и history_order_fk соответственно.

  • Может быть полезно создавать ограничения с помощью отдельных операторов. Создание таблиц, затем первичных ключей, а затем внешних ключей позволит избежать проблем с упорядочением зависимостей, указанных выше.
  • Вы пытаетесь создать циклические внешние ключи между LIBRARY_T и FORMATS . Вы можете сделать это, создав ограничения в отдельном операторе, но не делайте этого: у вас будут проблемы при вставке строк и, что еще хуже, проблемы с удалением. Вам следует пересмотреть свою модель данных и найти способ смоделировать отношения между двумя таблицами, чтобы одна была родительской, а другая — дочерней. Или, возможно, вам нужны отношения другого типа, например, таблица пересечений.
  • Избегайте пустых строк в ваших сценариях. Некоторые инструменты справятся с ними, а некоторые нет. Мы можем настроить SQL * Plus для их обработки, но лучше этого избежать.
  • Соглашение об именах LIBRARY_T уродливо. Попробуйте найти более выразительное имя, которое не требует лишнего суффикса, чтобы избежать столкновения ключевых слов.
  • T_CUSTOMERS еще уродливее, поскольку он несовместим с другими вашими таблицами и совершенно не нужен, поскольку customers не является ключевым словом.
  • Называть вещи сложно. Вы не поверите, сколько лет у меня были споры по поводу названий таблиц. Самое главное — последовательность. Если я смотрю на словарь данных и посмотреть таблицы называется T_CUSTOMERS и LIBRARY_T мой первый ответ будет путаница. Почему эти таблицы названы по-разному? Какую концептуальную разницу выражает это? Поэтому, пожалуйста, определитесь с соглашением об именах и придерживайтесь его. Сделайте имена таблиц в единственном или множественном числе. По возможности избегайте префиксов и суффиксов; мы уже знаем, что это таблица, нам не нужны a T_ или _TAB .

    Источник

    ORA-00907: missing right parenthesis

    I am trying to run the query below with the input values:

    :P6_QUICK_SELECT: This Year

    It tells me that i am missing a right parenthesis. I dont see where i am.

    Edited by: Dclipse03 on Jan 30, 2009 9:02 AM

    Best Answer

    Quick pointer — you may want to click on the «closing-quotes» icon on the rightmost side of your message box while replying. That makes it easy to differentiate the poster’s message from yours.

    So what’s the final word on this ?
    Does it work for you if you set the field as «display as text» and then use the PL/SQL block ?
    Or does it become a «select list» if you set the field as «display as text», and hence unsuitable for a PL/SQL block ?

    Here’s a very general idea.
    — Can you set the value of a text field as the return value of an Oracle function ? In other words, can your application call a function in order to set the value of a text field ?

    — Can you pass the value selected from a «select list» to an Oracle function ?

    If your answers for both these questions are «yes», then you could do something like the following.

    (1) Create two stored functions — «fn_from_date» and «fn_to_date» in the database. Each function takes in a string (varchar2) as the input value.
    (2) Set the value of the «text field» :P6_FROM_DATE as the return value of the function «fn_from_date».
    (3) Set the value of the «text field» :P6_TO_DATE as the return value of the function «fn_to_date».
    (4) Pass the value of «select list» :P6_QUICK_SELECT to each function.

    Make your application populate :P6_FROM_DATE and :P6_TO_DATE (by calling the functions «fn_from_date» and «fn_to_date») as soon as the end-user selects a value from the «select list» :P6_QUICK_SELECT». There must be some way of setting this — maybe as a property of the text field or something else.

    The functions could use the logic mentioned in the earlier post:
    Hope that helps,
    isotope

    Источник

    Oracle mechanics

    27.08.2009

    ora-904 ora-907 при использовании коррелированных подзапросов

    При использовании коррелированных подзапросов, т.е. подзапросов, результаты которых используются для каждой строки основного запроса — «a correlated subquery is evaluated once for each row», могут встречаются ошибки, неточно объясняющие, что делается неправильно

    ora-904 «%s: invalid identifier»

    ora-907 «missing right parenthesis»

    Первая ошибка ora-904 в случае correlated subquery при отсутствии синтаксических ошибок сообщает об использовании более, чем одного уровня глубины вложенности (N-th level sub-query):

    что не поддерживается Oracle (до версии 11.1.0.7 включительно) и стандартом SQL: ANSI SQL has table references (correlation names) scoped to just one level deep. Это пишет вице-президент Oracle T.Kyte, отвечая на соответствующий вопрос «Is there some sort of nesting limit for correlated subqueries?», т.е. информация официальная, из первых рук, пример оттуда же. В документации Oracle, начиная с 10.1, пишется иначе:

    Oracle performs a correlated subquery when a nested subquery references a column from a table referred to a parent statement any number of levels above the subquery

    — но, это, видимо, долгосрочные планы Oracle.

    ora-907

    тут проблема старая и известная: запрет на использование ORDER BY в подзапросах, описанная в документации Oracle 7 (в документации следующих версий уже не упоминается — видимо, тоже есть планы по исправлению):

    The ORDER BY clause cannot appear in subqueries within other statements.

    По вышеупомянутой ссылке на сайте asktom.oracle.com можно найти пример замены конструкции с ORDER BY типа:

    на аналитическую функцию типа :

    для одновременного понижения уровня вложенности подзапроса (correlated query level deep) до 1 и устранения проблемы с ORDER BY в подзапросе — конструкция dense_rank first ORDER BY допускается Oracle.

    Источник

    Ошибка Oracle — ORA-00907: отсутствует правая скобка

    Я ломаю голову над этой ошибкой Oracle. Следующий запрос отлично работает:

    Однако я хочу вернуть свой конкантонированный список в алфавитном порядке, потому что я такой разборчивый. Вы бы подумали, что я сделаю:

    Однако, когда я пытаюсь это сделать, я получаю сообщение об ошибке:

    Я могу запустить запрос в собственном операторе SELECT, например:

    И работает нормально. Мои скобки более сбалансированы, чем труппа Cirque du Soleil. Почему ошибка?

    Думаю, не получится. ORDER BY не влияет на агрегирование. Пожалуйста, протестируйте его, и, если необходимо, я опубликую определенную пользователем агрегатную функцию, которая выполняет сортировку. К сожалению, у меня нет версии, поддерживающей WM_CONCAT. — GolezTrol

    Подожди, ты прав. Все дело в споре, если я изменю автономный пример на ORDER BY NAME DESC то я получаю тот же результат. Я просто предположил, что это сработало, потому что значения оказались в алфавитном порядке. В любом случае я, вероятно, смогу просто отсортировать их с помощью простого выражения LINQ. — Mike Christensen

    Пример LISTAGG на эту страницу кажется, сортируется в алфавитном порядке, но я не очень хорошо знаком с этим синтаксисом, поэтому не уверен, можно ли это применить и к WM_CONCAT. Если нет, вы всегда можете использовать LISTAGG, и если это не сработает, я опубликую обходной путь позже сегодня. — GolezTrol

    2 ответы

    Я думаю, что ORDER BY не влияет на агрегированную функцию WM_CONCAT.

    Для этого, как и было обещано, настраиваемая агрегация, которая сортирует результаты. Может использоваться и в более ранних версиях.

    Теперь ваш запрос может выглядеть примерно так:

    Источник

    bestage

    0 / 0 / 0

    Регистрация: 26.04.2014

    Сообщений: 24

    1

    30.05.2014, 10:57. Показов 22454. Ответов 9

    Метки нет (Все метки)


    вот создаю таблицу из примера Грубера, выдает ошибку, хотя в упор не вижу где она

    SQL
    1
    2
    3
    4
    5
    6
    7
    
    CREATE TABLE salespeople(
    snum INT (4) NOT NULL,
    sname VARCHAR (15) NOT NULL,
    city VARCHAR (15) NOT NULL,
    comm DEC (4) NOT NULL,
    PRIMARY KEY(snum)
    );

    __________________
    Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



    0



    mlc

    25 / 25 / 10

    Регистрация: 20.09.2009

    Сообщений: 110

    30.05.2014, 11:05

    2

    Лучший ответ Сообщение было отмечено bestage как решение

    Решение

    у типа данных INT[EGER] нет таких параметров как precision, scale. Поэтому правильно будет так

    SQL
    1
    2
    3
    4
    5
    
    CREATE TABLE salespeople_test(
    snum INT  NOT NULL PRIMARY KEY,
    sname VARCHAR (15) NOT NULL,
    city VARCHAR (15) NOT NULL,
    comm DEC (4) NOT NULL)

    либо так

    SQL
    1
    2
    3
    4
    5
    
    CREATE TABLE salespeople_test(
    snum NUMBER(4)  NOT NULL PRIMARY KEY,
    sname VARCHAR (15) NOT NULL,
    city VARCHAR (15) NOT NULL,
    comm DEC (4) NOT NULL)



    1



    0 / 0 / 0

    Регистрация: 26.04.2014

    Сообщений: 24

    30.05.2014, 11:22

     [ТС]

    3

    спасибо, заработало

    Добавлено через 10 минут
    вот еще вопрос, создаю следующую таблицу , в поле odate обьявлять тип данных как data? а потом как вносить их туда командой insert?
    ================== ТАБЛИЦА 3: ПОРЯДКИ ==================

    ————————————————
    onum | amt | odate | cnum | snum
    ——-|————|————-|——|——
    3001 | 18.69 | 10/03/1990 | 2008 | 1007
    3003 | 767.19 | 10/03/1990 | 2001 | 1001
    3002 | 1900.10 | 10/03/1990 | 2007 | 1004
    3005 | 5160.45 | 10/03/1990 | 2003 | 1002
    3006 | 1098.16 | 10/03/1990 | 2008 | 1007
    3009 | 1713.23 | 10/04/1990 | 2002 | 1003
    3007 | 75.75 | 10/04/1990 | 2004 | 1002
    3008 | 4723.00 | 10/05/1990 | 2006 | 1001
    3010 | 1309.95 | 10/06/1990 | 2004 | 1002
    3011 | 9891.88 | 10/06/1990 | 2006 | 1001
    ————————————————



    0



    Grossmeister

    Модератор

    4186 / 3026 / 576

    Регистрация: 21.01.2011

    Сообщений: 13,096

    30.05.2014, 11:31

    4

    Цитата
    Сообщение от bestage
    Посмотреть сообщение

    потом как вносить их туда командой insert

    SQL
    1
    2
    
    INSERT INTO ...
    VALUES(... to_date('10.06.2014', 'dd.mm.yyyy') ....)

    PS
    У Oracle для числовых типов есть только тип NUMBER. Поэтому все типы INT, DEC, FLOAT, которые поддерживаются для совместимости с другими БД, все равно заменяются на NUMBER. Его лучше и использовать.



    0



    0 / 0 / 0

    Регистрация: 26.04.2014

    Сообщений: 24

    30.05.2014, 11:40

     [ТС]

    5

    я понял, а при создании таблицы, это поле odate как правильно обьвлять?



    0



    Grossmeister

    Модератор

    4186 / 3026 / 576

    Регистрация: 21.01.2011

    Сообщений: 13,096

    30.05.2014, 11:43

    6

    Цитата
    Сообщение от bestage
    Посмотреть сообщение

    это поле odate как правильно обьвлять

    Так и объявлять

    SQL
    1
    2
    3
    4
    5
    6
    
    CREATE TABLE tab1
    (
    ...
    odate DATE,
    ....
    )



    0



    0 / 0 / 0

    Регистрация: 26.04.2014

    Сообщений: 24

    30.05.2014, 15:22

     [ТС]

    7

    а вот как обьявлять десятичные числа чтобы после точки было 2 знака? я обьявил флоат — там округлило до одного знака, и еще формат даты поставил ддммгггг, переставило месяцы и дни местами.

    блин, и скрин как по человечески загрузить?))
    []http://cs619720.vk.me/v619720724/6775/G17_6FbJi1M.jpg[/]



    0



    25 / 25 / 10

    Регистрация: 20.09.2009

    Сообщений: 110

    30.05.2014, 15:29

    8

    Цитата
    Сообщение от bestage
    Посмотреть сообщение

    а вот как объявлять десятичные числа чтобы после точки было 2 знака?

    используйте number, как советовал Grossmeister. Например number(4,2).

    За отображение даты в определенном формате отвечают nls настройки.



    1



    Модератор

    4186 / 3026 / 576

    Регистрация: 21.01.2011

    Сообщений: 13,096

    30.05.2014, 15:33

    9

    Цитата
    Сообщение от bestage

    а вот как обьявлять десятичные числа чтобы после точки было 2 знака?

    Я уже сказал, что в Oracle для числового типа используется NUMBER. Если задашь просто NUMBER, то число знаков после запятой будет по дефолту. Если нужно не больше 2, тогда NUMBER(…, 2).

    Цитата
    Сообщение от bestage

    еще формат даты поставил ддммгггг, переставило месяцы и дни местами.

    Не понял, где ты поставил формат даты. Как вставлять дату в БД, я уже показал.



    1



    0 / 0 / 0

    Регистрация: 26.04.2014

    Сообщений: 24

    30.05.2014, 15:41

     [ТС]

    10

    спасибо, разобрался



    0



    Categories

    • 385.5K All Categories
    • 5.1K Data
    • 2.5K Big Data Appliance
    • 2.5K Data Science
    • 453.4K Databases
    • 223.2K General Database Discussions
    • 3.8K Java and JavaScript in the Database
    • 47 Multilingual Engine
    • 606 MySQL Community Space
    • 486 NoSQL Database
    • 7.9K Oracle Database Express Edition (XE)
    • 3.2K ORDS, SODA & JSON in the Database
    • 585 SQLcl
    • 4K SQL Developer Data Modeler
    • 188K SQL & PL/SQL
    • 21.5K SQL Developer
    • 46 Data Integration
    • 46 GoldenGate
    • 298.4K Development
    • 4 Application Development
    • 20 Developer Projects
    • 166 Programming Languages
    • 295K Development Tools
    • 150 DevOps
    • 3.1K QA/Testing
    • 646.7K Java
    • 37 Java Learning Subscription
    • 37.1K Database Connectivity
    • 201 Java Community Process
    • 108 Java 25
    • 8.1K Embedded Technologies
    • 22.2K Java APIs
    • 138.3K Java Development Tools
    • 165.4K Java EE (Java Enterprise Edition)
    • 22 Java Essentials
    • 176 Java 8 Questions
    • 86K Java Programming
    • 82 Java Puzzle Ball
    • 65.1K New To Java
    • 1.7K Training / Learning / Certification
    • 13.8K Java HotSpot Virtual Machine
    • 94.3K Java SE
    • 13.8K Java Security
    • 208 Java User Groups
    • 25 JavaScript — Nashorn
    • Programs
    • 667 LiveLabs
    • 41 Workshops
    • 10.3K Software
    • 6.7K Berkeley DB Family
    • 3.6K JHeadstart
    • 6K Other Languages
    • 2.3K Chinese
    • 207 Deutsche Oracle Community
    • 1.1K Español
    • 1.9K Japanese
    • 474 Portuguese

    user10274093

    Hi all,

    on 11.2.0.4 on Win 2008

    when running :

    select creele,TRUNC((creele,’DD’)) from emprunts;

    I receive :

    ORA-00907: missing right parenthesis (on column 28).

    Any idea ?

    Let’s see the format of creele :

    select creele from emprunts;

    CREELE

    ———

    11/10/14

    21/10/14

    Thanks.

    Best Answer

    • Chris Hunt


      Chris Hunt


      Freelance Oracle Consultant Leicester, UKMember Posts: 2,066 Gold Trophy

      Can you say me please why column A and B have different results :
      
      select  trunc(AVG(trunc(rendule,'DD')-trunc(creele+1,'DD')),2) A,         TRUNC(AVG(TRUNC(rendule,'DD')-TRUNC(creele,'DD')+1),2) B from details, emprunts WHERE details.emprunt=emprunts.numero       and emprunts.NUMERO = details.EMPRUNT       AND details.rendule is not null       GROUP BY membre;

      Because you’re telling it to do different things. Let’s suppose that there’s just one row in your table, with a rendule of 30/4/2015 and a creele of 20/4/2015.

      A = 30/4/2015 — (20/4/2015 + 1) = 30/4/2015 — 21/4/2015 = 9

      B = 30/4/2015 — 20/4/2015 + 1 = 10 + 1 = 11

      If you want arithmetic operations to be carried out in a particular order, it’s best to use parentheses to make the order unambiguous. This would return the same value as A (if that’s what you want):

      TRUNC(AVG(TRUNC(rendule,’DD’) — (TRUNC(creele,’DD’)+1)),2)

    «12»

    Answers

    • iKozheko

      just try this:

      select creele,TRUNC(creele,’DD’) from emprunts;

    • Shahasra

      do you want show only date- use to_char

      select sysdate, trunc(sysdate,’DD’) , to_char(sysdate,’DD’) from dual

    • Jarkko Turpeinen

      Hi

      select creele, TRUNC( (creele,'DD') ) from emprunts;
      
      I receive :
      ORA-00907: missing right parenthesis (on column 28).
      Any idea ?
      Let's see the format of creele :
      
      select creele from emprunts;
      CREELE
      --------
      11/10/14
      21/10/14
      
      Thanks.
      
      
      
      
      
      
      
      
      

      You try to add collection like values and syntax error is evident because single value or variable or expression is expected inside parenthesis. It is because parenthesis must return single result to upper nesting level (i might use wrong terms here because i did not find docs about this, yet)

      select trunc ( ( ( sysdate — 1 ) ) ) from dual; is legal because sysdate -1 is expression that returns single result.

      Date format is irrelevant and it depends session NLS_DATE_FORMAT setting how you see it.

      So to fix your problem you must remove one nesting level that is extra parenthesis around creele,’DD’

      Correct syntax is select creele, TRUNC( creele, ‘DD’ ) from emprunts;

      and with dates ‘DD’ is default for function TRUNC.

      so this returns same result select creele, TRUNC( creele ) from emprunts;

    • Etbin


      Etbin


      SloveniaMember Posts: 8,968 Gold Crown

      Assuming creele is a french translation of createdon then (most probably) we’re dealing with a date datatype.

      The rest depends on what you want:

      select dump(creele) creele_dump,

             to_char(creele,’dd/mm/yyyy’) creele,

             to_char(trunc(creele,’dd’),’dd/mm/yyyy’) one, — no need to use trunc (original truncated already)

             to_char(creele,’dd’) two

        from (select to_date(’21/10/14′,’dd/mm/rr’) creele

                from dual

             )

      CREELE_DUMP CREELE ONE TWO
      Typ=13 Len=8: 222,7,10,21,0,0,0,0 21/10/2014 10/21/2014 21

      Regards

      Etbin

    • Utsav


      Utsav


      New Delhi, IndiaMember Posts: 859 Silver Badge

      Error is getting generated due to bad syntax. Here your syntax says to oracle

      Trunc  then value inside () 

      But inside () oracle gets creele,’DD’

      So, as your creele is a date type column so oracle is expecting that as you have used TRUNC function, as it hits first opening bracket then second opening bracket follow by creele (datetype column) but no operation actually happening with date rather it got bad syntax ie. ,’DD’

      TRY

      select creele,TRUNC(creele,’DD’) from emprunts;

    • Jarkko Turpeinen

      Prashant Dabral kirjoitti:
      
      Error is getting generated due to bad syntax. Here your syntax says to oracle
      
      Trunc  then value inside ()  But inside () oracle gets creele,'DD' So, as your creele is a date type column so oracle is expecting that as you have used TRUNC function, as it hits first opening bracket then second opening bracket follow by creele (datetype column) but no operation actually happening with date rather it got bad syntax ie. ,'DD' TRY select creele,TRUNC(creele,'DD') from emprunts;

      Nothing to do with date.

      select (dummy, ‘DD’) from dual;

      SQL Error: ORA-00907: missing right parenthesis

      00907. 00000 —  «missing right parenthesis»

    • user10274093

      very nice explanation. Thank you. Can you say me please why column A and B have different results :

      select  trunc(AVG(trunc(rendule,’DD’)-trunc(creele+1,’DD’)),2) A,

              TRUNC(AVG(TRUNC(rendule,’DD’)-TRUNC(creele,’DD’)+1),2) B

      from details, emprunts

      WHERE details.emprunt=emprunts.numero

            and emprunts.NUMERO = details.EMPRUNT

            AND details.rendule is not null

            GROUP BY membre;

      ———- ———-

        8,66  10,66
      16,25  18,25
      14,25  16,25

      Thanks and regards.

    • Jarkko Turpeinen

      Looks like you trunc different creele values in those expressions.

      Other is creele +1 and the other plain creele.

      And the formula is different.

      Consider following:

      Column «A»

      trunc( sysdate ) — trunc( sysdate + 1 )

      Equals to expression

      select date ‘2015-01-01’ — date ‘2015-01-02’ from dual;

      that is -1

      Column «B»

      trunc( sysdate ) — trunc( sysdate ) + 1

      Equals to expression

      select date ‘2015-01-01’ — date ‘2015-01-01’ + 1 from dual;

      that is 0 + 1 = 1

    • Utsav


      Utsav


      New Delhi, IndiaMember Posts: 859 Silver Badge

      Again,

      select (‘a’,2) from dual — Will always gives us error, Its syntactical error and there could be lots of possiblity like is somebody forgot to use NVL,Greatest fucntion. So which possible syntax user wants how this can Oracle determine.

      select (‘a’),(2) from dual — Are two column are processed inside brackets and they the acutal output will let out.

    • Jarkko Turpeinen

      Prashant Dabral kirjoitti:
      
      Again,
      select ('a',2) from dual -- Will always gives us error, Its syntactical error and there could be lots of possiblity like is somebody forgot to use NVL,Greatest fucntion. So which possible syntax user wants how this can Oracle determine.
      
      select ('a'),(2) from dual -- Are two column are processed inside brackets and they the acutal output will let out.

      You are correct, it is syntax error. I misunderstood your explanation and that’s why i pointed out that it has nothing to do with date.

    This discussion has been closed.

    0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии

    А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Ora 00604 ошибка на рекурсивном sql уровне 1 ora 12705
  • Ora 12537 tns connection closed ошибка