Apex parse error when creating SQL query with sql function - sql

I have the following function:
CREATE OR REPLACE FUNCTION calc_a(BIDoctor number) RETURN number
IS
num_a number;
BEGIN
select count(NAppoint)
into num_a
from Appointment a
where BIDoctor = a.BIDoctor;
RETURN num_a;
END calc_a;
What we want is adding a column to a report that shows us the number of appointments that doc have.
select a.BIdoctor "NUM_ALUNO",
a.NameP "Nome",
a.Address "Local",
a.Salary "salary",
a.Phone "phone",
a.NumberService "Curso",
c.BIdoctor "bi",
calc_media(a.BIdoctor) "consultas"
FROM "#OWNER#"."v_Doctor" a, "#OWNER#"."Appointment" c
WHERE a.BIdoctor = c.BIdoctor;
and we got this when we are writing the region source on apex.
But it shows a parse error, I was looking for this about 2 hours and nothing.
Apex shows me this:
PARSE ERROR ON THE FOLLOWING QUERY

This is probably because of all your double quotes, you seem to have randomly cased everything. Double quotes indicate that you're using quoted identifiers, i.e. the object/column must be created with that exact name - "Hi" is not the same as "hi". Judging by your function get rid of all the double quotes - you don't seem to need them.
More generally don't use quoted identifiers. Ever. They cause far more trouble then they're worth. You'll know when you want to use them in the future, if it ever becomes necessary.
There are a few more problems with your SELECT statement.
You're using implicit joins. Explicit joins were added in SQL-92; it's time to start using them - for your future career where you might interact with other RDBMS if nothing else.
There's absolutely no need for your function; you can use the analytic function, COUNT() instead.
Your aliases are a bit wonky - why does a refer to doctors and c to appointments?
Putting all of this together you get:
select d.bidoctor as num_aluno
, d.namep as nome
, d.address as local
, d.salary as salary
, d.phone as phone
, d.numberservice as curso
, a.bidoctor as bi
, count(nappoint) over (partition by a.bidoctor) as consultas
from #owner#.v_doctor a
join #owner#.appointment c
on d.bidoctor = a.bidoctor;
I'm guessing at what the primary keys of APPOINTMENT and V_DOCTOR are but I'm hoping they're NAPPOINT and BIDOCTOR respectively.
Incidentally, your function will never have returned the correct result because you haven't limited the scope of the parameter in your query; you would have just counted the number of records in APPOINTMENT. When you're naming parameters the same as columns in a table you have to explicitly limit the scope to the parameter in any queries you write, for instance:
select count(nappoint) into num_a
from appointment a
where calc_a.bidoctor = a.bidoctor; -- HERE

Related

"Incorrect syntax" and "Cannot be bound" when adding alias to Grouping Sets?

I have a common column (Name0) that I need to select from one of my tables. So, I alias it out, but then it starts throwing errors. The two columns I try to select show they could not be bound, followed by my aggregate having syntax errors. Finally, the grouping by set alias' show incorrect syntax. I am at a loss.
Select I.ARPDisplayName0,
SR.name0 = coalesce(SR.name0,concat('Total ',sum(1)))
From v_GS_INSTALLED_SOFTWARE I
inner join v_R_System SR on SR.resourceID = I.ResourceID
inner join v_GS_OPERATING_SYSTEM OS on OS.ResourceID = I.ResourceID
WHERE
ARPDisplayName0 = 'Adobe Acrobat 9 Pro' or
ARPDisplayName0 = 'Bomgar' or
Caption0 = 'Microsoft Windows 7 Professional'
Group By Grouping Sets (
(I.ARPDisplayName0,SR.name0),
(I.ARPDisplayName0),
(OS.Caption0,SR.Name0),
(OS.Caption0)
()
);
Specific errors:
Incorrect Syntax expecting (or Select" in coalesce(SR.name0,concat('Total ',sum(1))) and in the grouping sets alias.
The other error is:
the Multipart Identifier could not be bound in the SELECT statement "I.ARPDisplayName0" and "SR.name0"
The issues arise from just from a simple misunderstanding of how to use alias.
When providing the name of an alias, you can choose to use either an = assignment or the (optional) keyword as - it's really personal preference which you use but I prefer the latter option and keep = for actually assigning values to local variables.
The line SR.name0 = coalesce(SR.name0,concat('Total ',sum(1))) is causing an error since SQL Server interprets the SR. as an alias reference itself which can't be used in this context - the intended name is just "name0"; constructing it as coalesce(SR.name0,concat('Total ',sum(1))) as name0 would make the intent clearer.
Likewise, when using brackets [] around object names, the alias dot-notation is not included, so [I.ARPDisplayName0] is just I.[ARPDisplayName0]; in this case the brackets are completely optional as they are only required if there is a clash with a reserved word eg [date] or the use of certain characters such as a space [my column name]. Again it's personal preference but I prefer to only use them where necessary to remove "noise" and improve readability.

MS Access query produces invalid procedure call

My query in access works fine if i only use the below query with a select statement. As soon as it becomes an append query it produces an "invalid procedure call" error.
I have narrowed down the offending columns as being "Publ" and "PublLong". Both are long text strings. If I remove these two columns the query updates without an error.
Here is a sample data point found in the [Bezeichung] Field:
publications.bank.com/publ-dl-ch/pdf/WhatsUp_20181113_en.pdf
I checked the table that it is being inserted to and the data types are the same nor did i see any other setting that would block the insertion.
How can i get it to work?
INSERT INTO tbl_MatomoRaw ( DownloadDate, IntExt, Publ, PublLong,
PublDate, [Language], Download_Visits, PublMonth )
SELECT
Date() AS DownloadDate,
Left([Bezeichnung],InStr([Bezeichnung],".")-1) AS IntExt,
Nz(Mid([Bezeichnung],InStrRev([Bezeichnung],"/")+1,InStr([Bezeichnung],"_")-
InStrRev([Bezeichnung],"/")-1),"") AS Publ,
Mid([Bezeichnung],InStrRev([Bezeichnung],"/")+1,InStrRev([Bezeichnung],"_")-
InStrRev([Bezeichnung],"/")-1) AS PublLong,
Mid([Bezeichnung],InStr([Bezeichnung],"_")+1,8) AS PublDate,
Mid([Bezeichnung],Len([Bezeichnung])-5,2) AS [Language],
xlsx_Output.[Eindeutige Downloads] AS Download_Visits,
Mid([Bezeichnung],InStr([Bezeichnung],"_")+1,6) AS PublMonth
FROM xlsx_Output
WHERE
(((Nz(Mid([Bezeichnung],InStrRev([Bezeichnung],"/")+1,InStr([Bezeichnung],"_")-
InStrRev([Bezeichnung],"/")-1),"")) Not Like "#Func!"));
#Func! indicates one of your functions is causing an error.
Your query uses multiple functions that run into trouble when your input doesn't meet that format, pre-filter instead of filtering on an error, since you can't filter on an error when appending:
INSERT INTO tbl_MatomoRaw ( DownloadDate, IntExt, Publ, PublLong,
PublDate, [Language], Download_Visits, PublMonth )
SELECT
Date() AS DownloadDate,
Left([Bezeichnung],InStr([Bezeichnung],".")-1) AS IntExt,
Nz(Mid([Bezeichnung],InStrRev([Bezeichnung],"/")+1,InStr([Bezeichnung],"_")-
InStrRev([Bezeichnung],"/")-1),"") AS Publ,
Mid([Bezeichnung],InStrRev([Bezeichnung],"/")+1,InStrRev([Bezeichnung],"_")-
InStrRev([Bezeichnung],"/")-1) AS PublLong,
Mid([Bezeichnung],InStr([Bezeichnung],"_")+1,8) AS PublDate,
Mid([Bezeichnung],Len([Bezeichnung])-5,2) AS [Language],
[Eindeutige Downloads] AS Download_Visits,
Mid([Bezeichnung],InStr([Bezeichnung],"_")+1,6) AS PublMonth
FROM (SELECT * FROM xlsx_Output WHERE Len(Bezeichnung) > 5 AND Bezeichnung LIKE "*?.?*" AND Bezeichnung LIKE "*_????????*" AND Bezeichnung LIKE "*?\?*")
WHERE
(((Nz(Mid([Bezeichnung],InStrRev([Bezeichnung],"/")+1,InStr([Bezeichnung],"_")-
InStrRev([Bezeichnung],"/")-1),"")) Not Like "#Func!"));
Since I don't know exactly where the errors occur, I can't write up a proper filter to identify them, but judging by your query they should include a slash and a symbol after that slash, an underscore and at least 8 symbols after that underscore, and a dot with at least one symbol before and after the dot.

Using JOIN in Query within MS Access 2016 for Fields in the Long Text Format

I have two queries which are almost identical. The only difference is the format of the fields being joined. One works, the other doesn't.
The query which JOINs two Integer fields works perfectly.
The query which JOINs two Long Text fields produces the following error:
"Cannot join on Memo, OLE, or Hyperlink Object (alarmlogwithstring2.[Tag_Value]=ECLString.[Tag_Value])."
Functional Query:
SELECT alarmlogwithdescs.TableIndex, alarmlogwithdescs.Date_Stamp, alarmlogwithdescs.Time_Stamp, alarmlogwithdescs.Tag_Name, alarmlogwithdescs.Tag_Value, ErrorCodeLookup.ErrorDescription
FROM ErrorCodeLookup INNER JOIN alarmlogwithdescs ON ErrorCodeLookup.[Tag_Value] = alarmlogwithdescs.[Tag_Value]
ORDER BY alarmlogwithdescs.TableIndex;
Nonfunctional Query:
SELECT alarmlogwithstring2.TableIndex, alarmlogwithstring2.Date_Stamp, alarmlogwithstring2.Time_Stamp, alarmlogwithstring2.Tag_Value, ECLString.ErrorDescription
FROM alarmlogwithstring2 INNER JOIN ECLString ON alarmlogwithstring2.[Tag_Value] = ECLString.[Tag_Value]
ORDER BY alarmlogwithstring2.TableIndex;
What I've Tried:
1.) I swapped the table following "FROM" to be ECLString with all necessary changes that should follow. (i.e. Then, after INNER JOIN I changed ECLString to be alarmlogwithstring2, etc...) This makes the two queries more identical, but shouldn't have an effect on the outcome. I did the same for the functional query just to be sure. The functional one still worked and the nonfunctional one still does not...
2.) I tried making my lookup table's Tag_Value field Short Text while keeping the actual data table's Tag_Value field Long Text. No effect.
3.) I tried changing the JOIN type when creating the relationship between the two tables. No effect.
4.) Changed alarmlogwithstring2.[Tag_Value]=ECLString.[Tag_Value]
to CAST(alarmlogwithstring2.[Tag_Value] AS varchar(max)) = CAST(ECLString.[Tag_Value] AS varchar(max)) and get the following error:
"Syntax error (missing operator) in query expression CAST(alarmlogwithstring2.[Tag_Value] AS varchar(max)) = CAST(ECLString.[Tag_Value] AS varchar(max))."
For whatever reason, after clicking "Ok" to close the error message the comma following SELECT alarmlogwithstring2.TableIndex, is highlighted, suggesting the missing operator is there. Okay?
Any help would be greatly appreciated. Thank you for your time!
Got it! Works for my situation, at least. Any other method for doing this would still be appreciated.
This works for me because my Tag_Value field contains text such as "Error0, Error1, Error2," etc...
So, I used the following code:
SELECT alarmlogwithstring2.TableIndex, alarmlogwithstring2.Date_Stamp, alarmlogwithstring2.Time_Stamp, alarmlogwithstring2.Tag_Value, ECLString.ErrorDescription
FROM alarmlogwithstring2 INNER JOIN ECLString ON Right( alarmlogwithstring2.[Tag_Value] , 1) = Right(ECLString.[Tag_Value], 1)
ORDER BY alarmlogwithstring2.TableIndex;
This works because of the integer on the end of my Tag_Value text. Using the Right(string,length) function causes only the integers within each value to be compared as they're all on the right-side of the value.
If your situation is similar to mine, then the code above is fine; however, if your number of error codes (or whatever) gets into the double digits, be sure to reflect this in the fields of both tables. (i.e. Make Error0 => Error00, make Error1 => Error01, etc...) within both tables and use Right(string,2) instead of Right(string,1). [Seems obvious, but may not be for everyone.]
However, this will NOT always be the case for me and everyone else. Someone may have pure text, for example. Thus, again, if you know of another, more general, solution, please, do let me know and I'll make your answer the answer for this question.
Thanks!
Got it. See below for general solution. It uses StrComp(string1,string2)=0 to match strings.
SELECT alarmlogwithstring2.TableIndex, alarmlogwithstring2.Date_Stamp, alarmlogwithstring2.Time_Stamp, alarmlogwithstring2.Tag_Name, alarmlogwithstring2.Tag_Value, ECLString.ErrorDescription
FROM alarmlogwithstring2 INNER JOIN ECLString ON StrComp(alarmlogwithstring2.[Tag_Value], ECLString.[Tag_Value]) = 0
ORDER BY alarmlogwithstring2.TableIndex;

Syntax error on WITH clause

I am working on a web app and there are some long winded stored procedures and just trying to figure something out, I have extracted this part of the stored proc, but cant get it to work. The guy who did this is creating alias after alias.. and I just want to get a section to work it out. Its complaining about the ending but all the curly brackets seem to match. Thanks in advance..
FInputs is another stored procedure.. the whole thing is referred to as BASE.. the result of this was being put in a temp table where its all referred to as U. I am trying to break it down into separate sections.
;WITH Base AS
(
SELECT
*
FROM F_Inputs(1,1,100021)
),
U AS
(
SELECT
ISNULL(q.CoverPK,r.CoverPK) AS CoverPK,
OneLine,
InputPK,
ISNULL(q.InputName,r.InputName) AS InputName,
InputOrdinal,
InputType,
ParentPK,
InputTriggerFK,
ISNULL(q.InputString,r.InputString) AS InputString,
PageNo,
r.RatePK,
RateName,
Rate,
Threshold,
ISNULL(q.Excess,r.Excess) AS Excess,
RateLabel,
RateTip,
Refer,
DivBy,
RateOrdinal,
RateBW,
ngRequired,
ISNULL(q.RateValue,r.RateValue) AS RateValue,
ngClass,
ngPattern,
UnitType,
TableChildren,
TableFirstColumn,
parentRatePK,
listRatePK,
NewParentBW,
NewChildBW,
ISNULL(q.SumInsured,0) AS SumInsured,
ISNULL(q.NoItems,0) AS NoItems,
DisplayBW,
ReturnBW,
StringBW,
r.lblSumInsured,
lblNumber,
SubRateHeading,
TrigSubHeadings,
ISNULL(q.RateTypeFK,r.RateTypeFK) AS RateTypeFK,
0 AS ListNo,
0 AS ListOrdinal,
InputSelectedPK,
InputVis,
CASE
WHEN ISNULL(NewChildBW,0) = 0
THEN 1
WHEN q.RatePK is NOT null
THEN 1
ELSE RateVis
END AS RateVis,
RateStatus,
DiscountFirstRate,
DiscountSubsequentRate,
CoverCalcFK,
TradeFilter,
ngDisabled,
RateGroup,
SectionNo
FROM BASE R
LEFT JOIN QuoteInputs Q
ON q.RatePK = r.RatePK
AND q.ListNo = 0
AND q.QuoteId = 100021 )
Well, I explained the issue in the comments section already. I'm doing it here again, so future readers find the answer more easily.
A WITH clause is part of a query. It creates a view on-the-fly, e.g.:
with toys as (select * from products where type = 'toys') select * from toys;
Without the query at the end, the statement is invalid (and would not make much sense anyhow; if one wanted a permanent view for later use, one would use CREATE VIEW instead).

Comparing Date Values in Access - Data Type Mismatch in Criteria Expression

i'm having an issue comparing a date in an access database. basically i'm parsing out a date from a text field, then trying to compare that date to another to only pull newer/older records.
so far i have everything working, but when i try to add the expression to the where clause, it's acting like it's not a date value.
here's the full SQL:
SELECT
Switch(Isdate(TRIM(LEFT(bc_testingtickets.notes, Instr(bc_testingtickets.notes, ' ')))) = false, 'NOT ASSIGNED!!!') AS [Assigned Status],
TRIM(LEFT(bc_testingtickets.notes, Instr(bc_testingtickets.notes, ' '))) AS [Last Updated Date],
bc_testingtickets.notes AS [Work Diary],
bc_testingtickets.ticket_id,
clients.client_code,
bc_profilemain.SYSTEM,
list_picklists.TEXT,
list_picklists_1.TEXT,
list_picklists_2.TEXT,
list_picklists_3.TEXT,
bc_testingtickets.createdate,
bc_testingtickets.completedate,
Datevalue(TRIM(LEFT([bc_TestingTickets].[notes], Instr([bc_TestingTickets].[notes], ' ')))) AS datetest
FROM list_picklists AS list_picklists_3
RIGHT JOIN (list_picklists AS list_picklists_2
RIGHT JOIN (list_picklists AS list_picklists_1
RIGHT JOIN (bc_profilemain
RIGHT JOIN (((bc_testingtickets
LEFT JOIN clients
ON
bc_testingtickets.broker = clients.client_id)
LEFT JOIN list_picklists
ON
bc_testingtickets.status = list_picklists.id)
LEFT JOIN bc_profile2ticketmapping
ON bc_testingtickets.ticket_id =
bc_profile2ticketmapping.ticket_id)
ON bc_profilemain.id =
bc_profile2ticketmapping.profile_id)
ON list_picklists_1.id = bc_testingtickets.purpose)
ON list_picklists_2.id = bc_profilemain.destination)
ON list_picklists_3.id = bc_profilemain.security_type
WHERE ( ( ( list_picklists.TEXT ) <> 'Passed'
AND ( list_picklists.TEXT ) <> 'Failed'
AND ( list_picklists.TEXT ) <> 'Rejected' )
AND ( ( bc_testingtickets.ticket_id ) <> 4386 ) )
GROUP BY bc_testingtickets.notes,
bc_testingtickets.ticket_id,
clients.client_code,
bc_profilemain.SYSTEM,
list_picklists.TEXT,
list_picklists_1.TEXT,
list_picklists_2.TEXT,
list_picklists_3.TEXT,
bc_testingtickets.createdate,
bc_testingtickets.completedate,
DateValue(TRIM(LEFT([bc_TestingTickets].[notes], Instr([bc_TestingTickets].[notes], ' '))))
ORDER BY Datevalue(TRIM(LEFT([bc_TestingTickets].[notes], Instr([bc_TestingTickets].[notes], ' '))));
the value i'm trying to compare against a various date is this:
DateValue(Trim(Left([bc_TestingTickets].[notes],InStr([bc_TestingTickets].[notes],' '))))
if i add a section to the where clause like below, i get the Data Type Mismatch error:
WHERE DateValue(Trim(Left([bc_TestingTickets].[notes],InStr([bc_TestingTickets].[notes],' ')))) > #4/1/2012#
i've even tried using the DateValue function around the manual date i'm testing with but i still get the mismatch error:
WHERE DateValue(Trim(Left([bc_TestingTickets].[notes],InStr([bc_TestingTickets].[notes],' ')))) > DateValue("4/1/2012")
any tips on how i can compare a date in this method? i can't change any fields in the database, ect, that's why i'm parsing the date in SQL and trying to manipulate it so i can run reports against it.
i've tried googling but nothing specifically talks about parsing a date from text and converting it to a date object. i think it may be a bug or the way the date is being returned from the left/trim functions. you can see i've added a column to the end of the SELECT statement called DateTest and it's obvious access is treating it like a date (when the query is run, it asks to sort by oldest to newest/newest to oldest instead of A-Z or Z-A), unlike the second column in the select.
thanks in advance for any tips/clues on how i can query based on the date.
edit:
i just tried the following statements in my where clause and still getting a mismatch:
CDate(Trim(Left([bc_TestingTickets].[notes],InStr([bc_TestingTickets].[notes],' ')))) > #4/1/2012#
CDate(Trim(Left([bc_TestingTickets].[notes],InStr([bc_TestingTickets].[notes],' ')))) >
CDate("4/1/2012") CDate(DateValue(Trim(Left([bc_TestingTickets].[notes],InStr([bc_TestingTickets].[‌​notes],' '))))) > #4/1/2012#
i tried with all the various combinations i could think of regarding putting CDate inside of DateValue, outside, ect. the CDate function does look like what i should be using though. not sure why it's still throwing the error.
here's a link to a screenshot showing the results of the query http://ramonecung.com/access.jpg. there's two screenshots in one image.
You reported you get Data Type Mismatch error with this WHERE clause.
WHERE DateValue(Trim(Left([bc_TestingTickets].[notes],
InStr([bc_TestingTickets].[notes],' ')))) > #4/1/2012#
That makes me wonder whether [bc_TestingTickets].[notes] can ever be Null, either because the table design allows Null for that field, or Nulls are prohibited by the design but are present in the query's set of candidate rows as the result of a LEFT or RIGHT JOIN.
If Nulls are present, your situation may be similar to this simple query which also triggers the data type mismatch error:
SELECT DateValue(Trim(Left(Null,InStr(Null,' '))));
If that proves to be the cause of your problem, you will have to design around it somehow. I can't offer a suggestion about how you should do that. Trying to analyze your query scared me away. :-(
It seems like you are having a problem with the type conversion. In this case, I believe that you are looking for the CDate function.
A problem might be the order of the date parts. A test in the Immediate window shows this
?cdate(#4/1/2012#)
01.04.2012
?cdate(#2012/1/4#)
04.01.2012
Write the dates backwards in the format yyyy/MM/dd and thus avoiding inadverted swapping of days and months!
DateValue("2012/1/4")
and
CDate(#2012/1/4#)