QuerySyntaxException when using SQL EXCEPT and count(*) - sql

I have a situation in Hibernate where I need to get the count(*) on a SQL EXCEPT query. Below is the query (imitated my original code):
String query = """
select count(*) as totalCount
from ( select distinct id from Employee
where name like '%Roger%
EXCEPT select distinct id from Manager ) Temporary
"""
Now, when I say:
hibernateSession.createQuery(query);
The below exception is thrown:
org.hibernate.hql.ast.QuerySyntaxException:
unexpected token: ( near line 1, column 36
My logs also show the below parsing errors when I catch the exception:
org.hibernate.hql.PARSER line 1:36: unexpected token: (
org.hibernate.hql.PARSER line 14:315: unexpected token: EXCEPT
org.hibernate.hql.PARSER line 15:68: unexpected token: from
I cannot avoid the count, WHERE or EXCEPT.

Because you're using hibernateSession.createQuery(query), hibernate is creating a query using HQL syntax, which doesn't work with your query, as you're using SQL syntax.
You most likely need to use something resembling hibernateSession.createSQLQuery(query).
For more on using native sql queries, see Native SQL in the Hibernate documentation.
The answers to this related question might also be useful.

Can you try this query instead? Replaced EXCEPT with NOT EXISTS.
String query = """
select count(*) as totalCount
from ( select distinct id from Employee as emp
where emp.name like '%Roger%
and not exists (
from Manager as m where emp.id = m.id
)
) Temporary
"""

Related

"Unhandled expression type" in SQL subquery

I am using XrmToolBox with SQL 4 CDS to make some edits to a user in MS Dynamics. I don't quite know where the error lies-- in the SQL expression? In the FetchXML that it gets converted to? Anyway, here's my expression:
INSERT INTO systemuser (
firstname,
lastname,
internalemailaddress,
departmentid,
internalspecialtyid)
VALUES (
'John',
'Smith',
'john.smith#example.com',
(SELECT TOP 1 departmentid FROM department WHERE name = 'Commercial'),
(SELECT TOP 1 internalspecialtyid FROM internal_specialties WHERE name = 'B2B Comms'));
When I run this, I get this message from XrmToolBox:
Unhandled expression type: (SELECT TOP 1 departmentid FROM department WHERE name = 'Commercial')
I really don't understand this. I can select the subquery and execute it to get one response back. I can take its results and make it a static (non-subquery) expression with no problem. But why isn't this working? I'm pretty new to SQL, assuming that's where the problem is, so I could easily misunderstand the subquery syntax.
The SQL 4 CDS tool attempts to provide as much a SQL implementation for CDS/Dataverse as possible but it's not perfect. Reach out to the tool author directly by opening an issue on the the SQL 4 CDS's GitHub page: https://github.com/MarkMpn/Sql4Cds/issues

SQL in Access 2003: INSERT INTO and multiple SELECT queries

I'm using Access 2003 (forced to do it due to retrocompatibility) to modify a 10 years old project, not made by me.
I encounter errors in executing this query:
INSERT INTO ClientiContratto ( ID, CLIENTE, DATA, PERIODO, IMPORTO, FATTURATO )
SELECT [Forms]![InserisciContratto]![Cliente] AS Espr1, (SELECT Nome from TAnagrafica WHERE TAnagrafica.IDAnagr = [Forms]![InserisciContratto]![Cliente]) AS Espr2, [Forms]![InserisciContratto]![Data] AS Espr3, [Forms]![InserisciContratto]![Periodo] AS Espr4, [Forms]![InserisciContratto]![Importo] AS Espr5, False AS Espr6;
That returns errors due to
(SELECT Nome from TAnagrafica WHERE TAnagrafica.IDAnagr = [Forms]![InserisciContratto]![Cliente]) AS Espr2
If I execute this query standalone, it works like a charm but when it comes to inserting the query into the INSERT INTO...SELECT statement, it returns (translated from italian):
Runtime error '3000': Reserved error (-3025): there are no messages
for this error.
The aim is to insert in a table some new values based on values found in the active form, and the part of code which isn't working should search into a table a value linked to the [InserisciContratto]![Cliente] actual value.
What am I doing wrong? Maybe is that because I cant execute a SELECT subquery in a previous SELECT query?
Any help would be appreciated.
You can work around the problem using a DLookUp instead of a subquery:
DLookUp("Nome", "TAnagrafica", "TAnagrafica.IDAnagr = [Forms]![InserisciContratto]![Cliente]")
Note that you can either use the DLookUp on a form control, or in a query. Both are valid. In the query, it'd look like this:
INSERT INTO ClientiContratto ( ID, CLIENTE, DATA, PERIODO, IMPORTO, FATTURATO )
SELECT [Forms]![InserisciContratto]![Cliente] AS Espr1, DLookUp("Nome", "TAnagrafica", "TAnagrafica.IDAnagr = [Forms]![InserisciContratto]![Cliente]") AS Espr2, [Forms]![InserisciContratto]![Data] AS Espr3, [Forms]![InserisciContratto]![Periodo] AS Espr4, [Forms]![InserisciContratto]![Importo] AS Espr5, False AS Espr6;
An alternate, common source of these kind of errors is that Access behaves finicky when using subqueries and not querying from a real table. You can easily work around that by using the subquery as the main query. Note that this does require the subquery to always return a result, else no row will be inserted:
INSERT INTO ClientiContratto ( ID, CLIENTE, DATA, PERIODO, IMPORTO, FATTURATO )
SELECT [Forms]![InserisciContratto]![Cliente] AS Espr1, Nome AS Espr2, [Forms]![InserisciContratto]![Data] AS Espr3, [Forms]![InserisciContratto]![Periodo] AS Espr4, [Forms]![InserisciContratto]![Importo] AS Espr5, False AS Espr6
FROM TAnagrafica
WHERE TAnagrafica.IDAnagr = [Forms]![InserisciContratto]![Cliente]

Getting error ORA-00909: invalid number of arguments

CREATE VIEW ITCC.release_testcase_count
AS
(
SELECT CONCAT(rtm.requirement_id,'-',tct.release_id) AS id,
rtm.requirement_id AS requirement_id,
tct.release_id AS release_id,
COUNT(tct.release_id) AS testcase_count
from testcase_version tcv
INNER JOIN tcr_catalog_tree_testcase tct ON tcv.id = tct.testcase_version_id
LEFT JOIN requirement_testcase_mapping rtm ON rtm.testcase_id=tcv.testcase_id
GROUP BY tct.release_id , rtm.requirement_id
);
same query is working for ms sql and my sql without any syntax error. i want to execute it in oracle as well but i am getting error for the same
The Oracle CONCAT function only takes two, not three or more, parameters. Instead of using CONCAT, just use the concatenation operator:
CREATE VIEW ITCC.release_testcase_count AS (
SELECT rtm.requirement_id || '-' || tct.release_id AS id,
...
)
Or, if you really want to use CONCAT here, then you may chain them together:
CREATE VIEW ITCC.release_testcase_count AS (
SELECT CONCAT(rtm.requirement_id, CONCAT('-', tct.release_id)) AS id,
...
)

Need help with error in Oracle SQL query

this is the query:
SELECT DISTINCT pprom.pk
FROM
(
SELECT
item_t0.SourcePK as pk
FROM
links item_t0
WHERE (? = item_t0.TargetPK AND item_t0.SourcePK in (?,?))
AND (item_t0.TypePkString=? )
UNION
SELECT
item_t1.TargetPK as pk
FROM
cat2prodrel item_t1
WHERE ( item_t1.SourcePK in (? ) AND item_t1.TargetPK in (?,?))
AND (item_t1.TypePkString=? )
) AS pprom
And this is the error:
ORA-00933: SQL command not properly ended
Any ideas what could be wrong?
Edit:
The question marks are replaced by PKs of the respective items:
values = [PropertyValue:8802745684882, PropertyValue:8796177006593, PropertyValue:8796201713665, 8796110520402, PropertyValue:8796125954190, PropertyValue:8796177006593, PropertyValue:8796201713665, 8796101705810]
Edit 2:
The query is executed deep inside some proprietary software system so I don't know exactly the code that runs it.
Edit 3:
I found one more query that's a little shorter but results in the same error message:
SELECT DISTINCT pprom.pk
FROM
(
SELECT
item_t0.SourcePK as pk
FROM
links item_t0
WHERE (? = item_t0.TargetPK AND item_t0.SourcePK in (?))
AND (item_t0.TypePkString=? )
) AS pprom
Using the following values:
values = [PropertyValue:8799960601490, PropertyValue:8796177006593, 8796110520402]
Edit 4
I found the SQL code that is sent to the db after replacing the values:
SELECT DISTINCT pprom.pk
FROM
(
SELECT
item_t0.SourcePK as pk
FROM
links item_t0
WHERE (8801631769490 = item_t0.TargetPK AND item_t0.SourcePK in (8796177006593))
AND (item_t0.TypePkString=8796110520402 )
) AS pprom
I also tried executing the inner SELECT statement and that alone runs ok and returns a single PK as a result.
I could not find any obvious syntax error in your query so I'd presume the issue is the client library you are using to convert the ? place holders into actual values. Your question edit displays a sort of dump where there are 8 integers but only 6 PropertyValue items. Make sure that's not the issue: IN (?, ?) requires 2 parameters.
Edit
Try removing the AS keyword when you assign an alias to the subquery:
SELECT DISTINCT pprom.pk
FROM
(
SELECT
item_t0.SourcePK as pk
FROM
links item_t0
WHERE (8801631769490 = item_t0.TargetPK AND item_t0.SourcePK in (8796177006593))
AND (item_t0.TypePkString=8796110520402 )
) AS pprom
^^

How do I execute different SELECT statements based on a CASE

I am facing a problem in executing queries with CASE statement.
Based on my condition,(for eg. length), I want to execute different SQL statement.
Problematic sample query is as follows:
select case
when char_length('19480821') = 8
then select count(1) from Patient
when char_length('19480821')=10
then select count(1) from Doctor
end
Exception:
[Error] Script lines: 1-5 --------------------------
Incorrect syntax near the keyword 'select'.
Msg: 156, Level: 15, State: 2
Server: sunsrv4z7, Line: 2
I am not able to correct the syntax. I am getting the string for char_length as input from the user.
How can I fire queries based on certain condition?
Is CASE the right choice ? Or do I have to use any other thing.
Just put opening and closing bracket around select statement resolve you problem
select
case when
char_length('19480821')=8 then
(select count(1) from Patient )
when
char_length('19480821')=10 then
(select count(1) from Doctor )
end
select
case when char_length('19480821')=8 then (select count(1) from Patient)
when char_length('19480821')=10 then (select count(1) from Doctor)
end
The problem is that you are missing opening and closing brackets in your nested 'Select' statements :)
Please do note that it is not a case STATEMENT, it is a case EXPRESSION. By enclosing the queries in parentheses, you are converting them (syntactically) to values.
This is similar in principle to a subquery, such as
" select name from Doctor where salary = (select max(salary) from Doctor)"
select
case when
LEN('1948082100')=8 then
(select 'HELLO' )
when
LEN('194808210')=10 then
(select 'GOODBYE')
end
Change the values to test results.