"Unhandled expression type" in SQL subquery - sql

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

Related

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]

Hybris flexible query is not working for Customer type

I run below query through
https://localhost:9002/console/flexsearch#
When I run below query there is no error
SELECT
*
FROM { Customer AS p}
where p_name IS NOT NULL
But, when I run this, it's giving me an error.
SELECT *
FROM { Customer AS p}
where {p_name} =' zohan'
Confused between flexible and SQL query?
Hybris use flexible query syntax where you can simply use TypeCode (Customer) and their attribute(name) to make the query. Hybris internally convert your query to the respective database syntax. In DB each column name is prefixed with p_. So if you want to directly use SQL query you should use p_name otherwise with flexible search use model attributes name (name in your case)
Flexible search syntax
SELECT * FROM {Customer} WHERE {name} IS NOT NULL
Or
SELECT * FROM {Customer AS c} WHERE {c.name} IS NOT NULL
SQL query
you can run from HAC > console > FlexibleSearch > SQL query
SELECT * FROM users WHERE p_name is not null
Refer FlexibleSearch Samples and other Tips and Tricks
When you use Flexible Search, you need to refer to attributes and types by their code. Hybris translates this query then to an sql query. So in your case:
SELECT * FROM {Customer AS p} WHERE {p.name} IS NOT NULL

SQL Select statement - base results upon the value of an alias within statement

I am trying to write a Select statement (comprised of around 20 different joined aliases) that will only return results if the value of one of the aliases created within the same statement equals a certain value.
I'm very green with SQL at this point and therefore don't really know how to phrase this dilemma properly to find the answer elsewhere.
Current code for element being assigned an alias of "cmp_freq":
ISNULL((SELECT GroupValue FROM ClientGroup WHERE ClientKey = c.ClientKey AND GroupCode = 'CMP-FREQ'),'PLEASE UPDATE FIELD') AS cmp_freq
Essentially, I only want results returned for the entire statement where the value of cmp_freq is "30". Is there any way to reference this alias in the where clause of the statement as a whole in order to accomplish this?
There are several ways to accomplish your goal. One way would be to wrap your query in a SELECT and use a WHERE clause, like so:
SELECT i.cmp_freq
FROM (
/* Your existing query */
SELECT
ISNULL((SELECT GroupValue FROM ClientGroup WHERE ClientKey = c.ClientKey AND GroupCode = 'CMP-FREQ'),'PLEASE UPDATE FIELD') AS cmp_freq
FROM MyTable c
) i
WHERE i.cmp_freq = 30
It's difficult to offer other options as there is not enough information in your question.

QuerySyntaxException when using SQL EXCEPT and count(*)

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
"""

Issue when converting SQL to LINQ

I am attempting to convert a SQL stored procedure to LINQ to do some performance testing (trying to figure out if using LINQ in some of our methods will speed things up at all)
I am fairly new to doing anything in LINQ so I am just modifying examples in books / online to suit my needs and am stuck on something.
I have this code so far:
DIM TicketID as INTEGER = 1
DIM s =
FROM User in PersonnelTbl
WHERE !(from t in tblSupportTicketNotifications where t.TicketID = TicketID select t.EmployeeID).Contains(User.EmployeeID)
Select user
Im not sure why but I get an Identifier expected error message on the Where clause line. Can anyone point me in the right direction? Cheers
I've based my code so far on this example:
var query =
from c in dc.Customers
where !(from o in dc.Orders
select o.CustomerID)
.Contains(c.CustomerID)
select c;
This is what I am trying to convert
CREATE PROCEDURE spGetEmployeesToBeNotified
(
#TicketID INT
)
AS
BEGIN
SELECT
ID,
FirstName,
Surname,
FirstName+' '+Surname As FullName,
WorkEmail,
0 AS Checked
FROM
PersonnelTbl
WHERE
ID NOT IN(SELECT EmployeeID FROM tblSupportTicketNotifications WHERE TicketID = #TicketID)
AND
(FirstName IS NOT NULL
AND
FirstName <> ''
AND
Surname IS NOT NULL
AND
Surname <> '')
UNION
SELECT
person.ID,
person.FirstName,
person.Surname,
person.FirstName +' '+person.Surname As FullName,
person.WorkEmail,
1 AS Checked
FROM
PersonnelTbl person
JOIN
tblSupportTicketNotifications notify
ON
person.ID = notify.EmployeeID
WHERE
TicketID = #TicketID
ORDER BY
FirstName ASC,
Surname ASC
END
Assuming you have an association between User and SupportTicketNotifications, you could try the following which should use an Exists clause rather than In. You can then profile the differences in SQL to see which one actually works faster (or if the SQL engine optimizes them to the same things.)
DIM TicketID as INTEGER = 1
DIM s =
FROM User in PersonnelTbl
WHERE Not User.SupportTicketNotifications.Any(Function(t) t.TicketID = TicketID)
' The Select is optional in VB if you are just returning the item you are selecting.
Regarding performance with LINQ to SQL as compared to raw ADO, you may want to check out http://blogs.msdn.com/ricom/archive/2007/06/22/dlinq-linq-to-sql-performance-part-1.aspx. As you are learning LINQ, you should make an effort to profile what you are doing in any regard to help you learn what's happening and where you need to make performance improvements (including using Stored Procs/custom ADO where necessary).
Linq-2-sql will NEVER outperform a stored procedure.
In the end, all what Linq-2-sql does is give you a more object oriented approach but in the end it IS SQL that is being send to the database. So if you put the same SQL in the stored procedure it by definition is at least equally fast.
! is a C# operator. You want "Not" instead for VB.Net.