I have an application which automatically add brackets after WHERE condition and send it to JDBC Oracle driver, Oracle doesn't like it and thrown: ORA-00907: missing right parenthesis
I'm not sure how to work with it in the scope of Oracle syntax, but any suggestion to fix it having this brackets or it's not supported by the syntax?
Original query works just fine:
SELECT count(*) as ErrorCount, Engine_name, to_char(log_time,'hh24') as Hour FROM eailog_data.err_log WHERE err_timestamp > sysdate-1/24 GROUP BY engine_name, to_char(log_time,'hh24') HAVING count(*) > 100 AND count(*) > 0 ORDER BY count(*)
and 3rd party application modify it like this (note brackets added after WHERE condition):
SELECT count(*) as ErrorCount, Engine_name, to_char(log_time,'hh24') as Hour
FROM eailog_data.err_log
WHERE
(
err_timestamp > sysdate-1/24
GROUP BY engine_name,
to_char(log_time,'hh24')
HAVING count(*) > 100
)
AND count(*) > 0
ORDER BY count(*)
Any ideas how to fix SQL with added brackets?
The WHERE clause parenthetical expression needs to end at the end of the WHERE clause and the condition in the HAVING clause ends with a parenthesis, but never begins.
In terms of adding parenthesis, certainly you could add a parenthesis at the end of the WHERE clause and add a parenthesis at the beginning of the HAVING clause as follows:
SELECT count(*) AS errorcount,
engine_name,
to_char(log_time,'hh24') AS HOUR
FROM eailog_data.err_log
WHERE ( err_timestamp > SYSDATE-1/24 )
GROUP BY engine_name,
to_char(log_time,'hh24')
HAVING ( count(*) > 100 )
AND count( *) > 0
ORDER BY count(*)
Since this is an application, it sounds like you need to work with the author of the application to fix their parenthesis usage.
Here is an example using the DUAL table
Before, malformed parenthetical expression in the WHERE and HAVING clause.
SCOTT#dev> SELECT dummy,
2 COUNT(*)
3 FROM dual
4 WHERE (dummy != 'Y'
5 GROUP BY dummy
6 HAVING COUNT( *) = 1)
7 AND COUNT( *) > 0
8 ORDER BY COUNT(*)
9 /
WHERE (dummy != 'Y'
*
ERROR at line 4:
ORA-00907: missing right parenthesis
After, corrected parenthetical expression in the 'WHERE' and 'HAVING' clause.
SCOTT#dev> --corrected
SCOTT#dev> SELECT dummy,
2 COUNT(*)
3 FROM dual
4 WHERE (dummy != 'Y')
5 GROUP BY dummy
6 HAVING (COUNT( *) = 1)
7 AND COUNT( *) > 0
8 ORDER BY COUNT(*)
9 /
D COUNT(*)
= ==========
X 1
A SQL statement consists of several clauses (some of which are optional):
the column list
the table list (FROM clause)
filter conditions (WHERE clause)
aggregate columns (GROUP BY clause)
aggregate conditions (HAVING clause)
etc.
The key concept that seems to be missing is that you can't open a parenthesis in one clause and close it in another. The reason the error you're getting is "missing right parenthesis" is that the SQL engine thinks you're done with the WHERE clause as soon as it sees GROUP BY. Since there was a un-closed parenthetical at that point, it can't parse any further.
To use an analogy, the SQL you provided is like having the opening and closing parenthesis in different methods in Java. It simply can't work.
There are at least two ways to get around some tool mangling your SQL syntax: Creative SQL to subvert the parser, and convert the SQL.
Creative SQL
Parsing Oracle SQL is virtually impossible to do 100% correctly since the syntax is much more complicated than other languages. This leads to problems with beautifiers and code generators. I've seen tools fail in ways very similar to your example.
But this complexity also offers many opportunities to subvert tools that try to rewrite SQL. Try different features until you find something that is immune to their parser. Here are some ideas:
Inline view. select * from (select ... from ... where ... ) where 1=1;
Common table expression. with some_query as (select ... from ... where ... ) select * from some_query;
Alternative quoting mechanism.
select dummy
from dual
where '''' = q'<'>' --The parser probably thinks this is still a string.
and 1 = 1
group by dummy
--' --And it probably thinks this is the end.
Convert SQL
In extreme cases there are ways to make Oracle accept completely broken SQL. Check out
SQL Translation Framework
and DBMS_ADVANCED_REWRITE.
Those tools are definitely a last resort. It would be great if we could wave a magic wand and fix all 3rd party programs but we have to live in the real world.
Related
See title.
This is what I'm trying:
select a.work_order_no
from (
select work_order_no as work_order_no
from work_order_line
where insert_timestamp is not null
FETCH FIRST 1 ROWS ONLY
union all
select work_order_no as work_order_no
from work_order_line
where insert_timestamp is null
FETCH FIRST 1 ROWS ONLY
) as a
FETCH FIRST 1 ROWS ONLY
But it give the following error:
SQL State: 42601 Vendor Code: -199 Message: [SQL0199] Keyword UNION not expected. Valid tokens: ). Cause . . . . . : The keyword UNION was not expected here. A syntax error was detected at keyword UNION. The partial list of valid tokens is ). This list assumes that the statement is correct up to the unexpected keyword. The error may be earlier in the statement but the syntax of the statement seems to be valid up to this point. Recovery . . . : Examine the SQL statement in the area of the specified keyword. A colon or SQL delimiter may be missing. SQL requires reserved words to be delimited when they are used as a name. Correct the SQL statement and try the request again. Processing ended because the highlighted statement did not complete successfully Failed statements: 1
In SQL this concept would work with the 'top 1' syntax. I'm assuming this can also work in DB2 but I'm just doing something wrong with the syntax order?
I have asked a colleague and luckily he responded rather quickly:
I missed some ()
select a.work_order_no
from (
(select work_order_no as work_order_no
from work_order_line
where insert_timestamp is not null
FETCH FIRST 1 ROWS ONLY)
union all
(select work_order_no as work_order_no
from work_order_line
where insert_timestamp is null
FETCH FIRST 1 ROWS ONLY )
) as a
FETCH FIRST 1 ROWS ONLY
I'm new to Oracle and recently ran into the following query. I'm trying to understand what it's doing and hopefully rewrite it to optimize it. In this example, :NameList would be a comma separated list (like: "Bob,Bill,Fred") and then :N_NameList would be the number of tokens (in above example, 3)
SELECT ... FROM
(
SELECT
REGEXP_SUBSTR(:NameList,'[^,]+',1,LEVEL, 'i') Name
FROM DUAL CONNECT BY LEVEL <= :N_NameList
) x
INNER JOIN PEOPLE ppl
ON ppl.Name LIKE x.Name
...
From what I can tell, it expands out the delimited list into unique rows and then joins it with the following tables for each name, but I'm not sure if that's all it's doing. If that is the case, is there a better way to accomplish this?
You could try this instead:
select ...
from people ppl
where instr (','||:NameList||',',
','||ppl.name||',') > 0;
is there a better way to accomplish this?
Well, you could get rid of N_NameList because you can easily count number of tokens. This doesn't mean that it is a better way, it's just a different option. To be honest, it is probably slower option than yours as I have to calculate something that you entered as a parameter.
As this example is based on SQLPlus, I've used & instead of : for substitution variables. && means that it'll "remember" previously entered value (otherwise, I should type NameList twice.
Your current query:
SQL> select regexp_substr('&namelist', '[^,]+', 1, level, 'i') name
2 from dual
3 connect by level <= &n_namelist;
Enter value for namelist: Bob,Bill,Fred
Enter value for n_namelist: 3
Bob
Bill
Fred
Calculated N_NameList (using REGEXP_COUNT):
SQL> select regexp_substr('&&namelist', '[^,]+', 1, level, 'i') name
2 from dual
3 connect by level <= regexp_count('&&namelist', ',') + 1;
Enter value for namelist: Bob,Bill,Fred
Bob
Bill
Fred
I'm wondering if it's possible to pass one or more parameters to a WITH clause query; in a very simple way, doing something like this (taht, obviously, is not working!):
with qq(a) as (
select a+1 as increment
from dual
)
select qq.increment
from qq(10); -- should get 11
Of course, the use I'm going to do is much more complicated, since the with clause should be in a subquery, and the parameter I'd pass are values taken from the main query....details upon request... ;-)
Thanks for any hint
OK.....here's the whole deal:
select appu.* from
(<quite a complex query here>) appu
where not exists
(select 1
from dual
where appu.ORA_APP IN
(select slot from
(select distinct slots.inizio,slots.fine from
(
with
params as (select 1900 fine from dual)
--params as (select app.ora_fine_attivita fine
-- where app.cod_agenda = appu.AGE
-- and app.ora_fine_attivita = appu.fine_fascia
--and app.data_appuntamento = appu.dataapp
--)
,
Intervals (inizio, EDM) as
( select 1700, 20 from dual
union all
select inizio+EDM, EDM from Intervals join params on
(inizio <= fine)
)
select * from Intervals join params on (inizio <= fine)
) slots
) slots
where slots.slot <= slots.fine
)
order by 1,2,3;
Without going in too deep details, the where condition should remove those records where 'appu.ORA_APP' match one of the records that are supposed to be created in the (outer) 'slots' table.
The constants used in the example are good for a subset of records (a single 'appu.AGE' value), that's why I should parametrize it, in order to use the commented 'params' table (to be replicated, then, in the 'Intervals' table.
I know thats not simple to analyze from scratch, but I tried to make it as clear as possible; feel free to ask for a numeric example if needed....
Thanks
Firstly, I greatly appreciate any feedback that anyone can offer. I am using Oracle SQL Developer, Version 4.0.2.15, Build 15.21.
I know and understand that many, many similar questions have been asked, as I've searched around on stackoverflow as well as the rest of the internet. However, the corresponding answers are either too vague or too extravagant, and attempt to do things that are way over my head and not what I am trying to accomplish. I am extremely new to SQL and haven't seriously done any coding since I did Java about 12 years ago. So please understand that something simple to you, is not so simple and obvious to me.
My bare-bones endstate that I am shooting for is taking a pre-existing Oracle Table Column, which is called 'service_level', that has parameters of 1-3, and making them A-C (where A=1, B=2, C=3). The reason for this is that I have an ArcGIS gdB featureclass that has a corresponding column, called 'MaintServi', with the parameters of A-C. I am going to join them using ArcToolbox once I have converted/replaced the 1-3 to A-C, and have exported them from Oracle into an Arc gdB as another table. The reason being is that the featureclass (obviously) has geometry, but this particular Oracle table does not.
From what I have gathered I know (or think) I will need to use something like:
chr(ord('a') + 3)
^ Where I will need to use/call upon the chr/ord functions. However, due to my inexperience, I cannot think of how to properly call this without getting an error. Below is what I have for my query thus far (but without chr/ord). I just need to figure out how to correctly insert it into my query to achieve the desired results.
SELECT v_wv_wp_crew.*,
Substr(v_wv_wp_crew.winter_supp_id, 1, 6) AS CostCenter,
Substr(v_wv_wp_crew.winter_supp_id, 8, 11) AS Crew_Supp_ID
FROM v_wv_wp_crew
WHERE crew_on_road >= '13-FEB-12'
AND ( operation = 2
OR operation = 3 );
Thanks again and hopefully I have complied with the posting rules of stackoverflow.
# Mark J. Bobak -
When implementing his ideas I get either this (Like I said, i'm not sure how to insert it properly without receiving an error)
SELECT v_wv_wp_crew.*,
Substr(v_wv_wp_crew.winter_supp_id, 1, 6) AS CostCenter,
Substr(v_wv_wp_crew.winter_supp_id, 8, 11) AS Crew_Supp_ID
FROM v_wv_wp_crew
WHERE crew_on_road >= '13-FEB-12'
AND ( operation = 2
OR operation = 3 )
UNION ALL
WITH service_level as (select 1 service_level from dual
union all
select 2 service_level from dual union all
select 3 service_level from dual)
select decode(service_level,1,'A',2,'B',3,'C') from service_level;
I receive the following error:
*ORA-32034: unsupported use of WITH clause
32034. 00000 - "unsupported use of WITH clause"
*Cause: Inproper use of WITH clause because one of the following two reasons
1. nesting of WITH clause within WITH clause not supported yet
2. For a set query, WITH clause can't be specified for a branch.
3. WITH clause can't sepecified within parentheses.
Action: correct query and retry
Error at Line: 14 Column: 25
Or I receive an output of only 3 rows (A, B, C) if I run the query separately - sorry I don't have enough reputation to post the image yet.
You can use the DECODE() function. Something like this should work:
with list_of_digits as (select 1 col_a from dual
union all
select 2 col_a from dual
union all
select 3 col_a from dual
union all
select 4 col_a from dual)
select decode(col_a,1,'A',2,'B',3,'C','Other') from list_of_digits;
Using your query, try this:
WITH service_level as (select 1 service_level from dual
union all
select 2 service_level from dual union all
select 3 service_level from dual)
select decode(service_level,1,'A',2,'B',3,'C') from service_level
union all
SELECT v_wv_wp_crew.*,
Substr(v_wv_wp_crew.winter_supp_id, 1, 6) AS CostCenter,
Substr(v_wv_wp_crew.winter_supp_id, 8, 11) AS Crew_Supp_ID
FROM v_wv_wp_crew
WHERE crew_on_road >= '13-FEB-12'
AND ( operation = 2
OR operation = 3 );
ord isn't an Oracle function. The equivalent Oracle function is ASCII. However, even substituting in the correct function, I don't see how that gets you what you want.
It seems most likely that you just want to add a column (I'd use case to translate the values):
SELECT v_wv_wp_crew.*,
Substr(v_wv_wp_crew.winter_supp_id, 1, 6) AS CostCenter,
Substr(v_wv_wp_crew.winter_supp_id, 8, 11) AS Crew_Supp_ID,
case service_level
when '1' then 'a'
when '2' then 'b'
when '3' then 'c'
end as service_level_alpha
FROM v_wv_wp_crew
WHERE crew_on_road >= '13-FEB-12'
AND ( operation = 2
OR operation = 3 );
If you want to return this column as service_level, then you'll need to return the full list of columns instead of using the asterisk.
Since this is a straight-forward character swap, you could use translate to really streamline the operation: translate(service_level,'123','abc'). However, I vastly prefer case over either decode or translate for readability
For a pair of cursors where the total number of rows in the resultset is required immediately after the first FETCH, ( after some trial-and-error ) I came up with the query below
SELECT
col_a,
col_b,
col_c,
COUNT(*) OVER( PARTITION BY 1 ) AS rows_in_result
FROM
myTable JOIN theirTable ON
myTable.col_a = theirTable.col_z
GROUP BY
col_a, col_b, col_c
ORDER BY
col_b
Now when the output of the query is X rows, rows_in_result reflects this accurately.
What does PARTITION BY 1 mean?
I think it probably tells the database to partition the results into pieces of 1-row each
It is an unusual use of PARTITION BY. What it does is put everything into the same partition so that if the query returns 123 rows altogether, then the value of rows_in_result on each row will be 123 (as its alias implies).
It is therefore equivalent to the more concise:
COUNT(*) OVER ()
Databases are quite free to add restrictions to the OVER() clause. Sometimes, either PARTITION BY [...] and/or ORDER BY [...] are mandatory clauses, depending on the aggregate function. PARTITION BY 1 may just be a dummy clause used for syntax integrity. The following two are usually equivalent:
[aggregate function] OVER ()
[aggregate function] OVER (PARTITION BY 1)
Note, though, that Sybase SQL Anywhere and CUBRID interpret this 1 as being a column index reference, similar to what is possible in the ORDER BY [...] clause. This might appear to be a bit surprising as it imposes an evaluation order to the query's projection. In your case, this would then mean that the following are equivalent
COUNT(*) OVER (PARTITION BY 1)
COUNT(*) OVER (PARTITION BY col_a)
This curious deviation from other databases' interpretation allows for referencing more complex grouping expressions.