I am trying to make a query through a button; though it says
Syntax error in JOIN operation. When I click it... I can't find the syntax error, maybe you guys can help me out? This is the code:
Set qdef = CurrentDb.CreateQueryDef("UnitMoreInfoQ", _
"SELECT UnitsT.*, WorkOrdersQ.CustomerName, WorkOrdersQ.ClientName, WorkOrdersQ.WorkOrderNumber " & _
"FROM UnitsT inner join workordersQ on WorkOrdersT.WorkOrerID=WorkOrdersQ.WorkOrderID " & _
"WHERE UnitsT.UnitID = " & txtWorkOrderID.Value)
The problem seems to be with your JOIN condition:
WorkOrdersT.WorkOrerID=WorkOrdersQ.WorkOrderID
There isn't a WorkOrdersT table or table alias defined in the FROM or other join, so your query isn't valid.
Make it easier on yourself to find and fix SQL errors.
Use a string variable to hold the SQL statement your code constructs. You can Debug.Print that statement before using it with CreateQueryDef. Then when troubleshooting, go to the Immediate window (Ctrl+g) to examine the statement your code is attempting to use. You can copy it from there and then paste it into SQL View of a new query for further testing. And if you need help, show us the completed statement text instead of the VBA code which builds the statement.
Dim strSelect As String
strSelect = "SELECT u.*, w.CustomerName, w.ClientName, w.WorkOrderNumber " & _
"FROM UnitsT As u inner join workordersQ AS w " & _
"on u.WorkOrerID=w.WorkOrderID " & _
"WHERE u.UnitID = " & txtWorkOrderID.Value
Debug.Print strSelect
Set qdef = CurrentDb.CreateQueryDef("UnitMoreInfoQ", strSelect)
Alternatively, use the query designer to create the query you need from scratch. Once you get that working, switch to SQL view, copy the statement text, and revise your VBA code to create the same statement.
Related
I'm trying to attach a SELECT query to a VBA object in Access, but I keep getting the error:
Syntax Error in Join operation
Dim sql As String
sql = "SELECT R_History.iteration, R.RuntimeID, Policylanguage.FormBody " & _
"FROM PolicyLanguage " & _
"INNER JOIN ([Policy&Elements] " & _
"INNER JOIN ((R " & _
"INNER JOIN R_History " & _
"ON (R.RunTimeID = R_History.RunTimeID " & _
"AND (R.ReportID = R_History.ReportID)) " & _
"INNER JOIN StatePolicyLanguage " & _
"ON R_History.Iteration = StatePolicyLanguage.Iteration) " & _
"ON [Policy&Elements].[Text&ElementID] = StatePolicyLanguage.[TextID&ElementID] " & _
"ON PolicyLanguage.TextID = [Policy&Elements].TextID " & _
"WHERE (((R.RuntimeID) = Dlast('runtimeID','r')));"
DoCmd.RunSQL (sql)
I can't get this to run for the absolute life of me. Can anyone tell what's wrong?
Edit: Here is the code I am trying to emulate
If you're running a query where the criteria are values entered in a form (e.g. field1 = frm1.txtValue), you could create a parameterized query where the passed parameters are added to the WHERE clause. That way, you don't have create SQL in VBA---you'd just have to set the parameters in VBA.
As noted by others, Access requires you to put parentheses after each join:
from (((Table1
inner join Table2 on Table2.field1 = Table1.field1)
inner join Table3 on Table3.field2 = Table2.field2)
inner join Table4 on Table4.field3 = Table3.field3)
So, as suggested by others, if you absolutely need to construct the query via VBA, keep your JOIN and ON clauses together to prevent confusion, and add the necessary parentheses.
I've found when you have to create complex queries in Access (either in the SQL editor or in VBA), it can be helpful to write the SQL in a more friendly editor (e.g. Notepad++) that supports things like syntax highlighting. Then, you can paste the query where it needs to go.
I need a second set of eyes on this SQL query embedded in the VBA code. I'm making an MS Access app that returns a dataset based on the to & from date criteria set by the user in the specific date picker boxes. The sql query that you see actually has been tested statically within MS Access query design view. I tested it with actual dates where you see the Me.from_filter and Me.to_filter. It worked perfectly! If you chose something like from 1/1/2015 to 5/1/2015 it returns columns of all the months you need. Perfect. Now when I embed it in the VBA code and assign it to a control variable, I get the "Run-time error '2342': A RunSQL action requires an argument consisting of an SQL statement." Can someone please eyeball this and tell me what might be wrong?
Option Compare Database
Option Explicit
Dim strSQL As String
Private Sub Command0_Click()
If IsNull(Me.from_filter) Or IsNull(Me.to_filter) Then
MsgBox "You have not entered a start date or end date"
Else
strSQL = "TRANSFORM Sum(dbo_ASSET_HISTORY.MARKET_VALUE) AS SumOfMARKET_VALUE " _
& "SELECT [dbo_FIRM]![NAME] AS [FIRM NAME], dbo_FUND.CUSIP, dbo_FUND.FUND_NAME, dbo_FUND.PRODUCT_NAME " _
& "FROM (dbo_ASSET_HISTORY INNER JOIN dbo_FIRM ON dbo_ASSET_HISTORY.FIRM_ID = dbo_FIRM.FIRM_ID) INNER JOIN dbo_FUND ON dbo_ASSET_HISTORY.FUND = dbo_FUND.FUND " _
& "WHERE (((dbo_FIRM.Name) Like 'Voya F*') And ((dbo_ASSET_HISTORY.PROCESS_DATE) >= #" & Me.from_filter & "# And (dbo_ASSET_HISTORY.PROCESS_DATE) <= #" & Me.to_filter & "#)) " _
& "GROUP BY [dbo_FIRM]![NAME], dbo_FUND.CUSIP, dbo_FUND.FUND_NAME, dbo_FUND.PRODUCT_NAME " _
& "PIVOT [dbo_ASSET_HISTORY]![ASSET_YEAR] & '-' & [dbo_ASSET_HISTORY]![ASSET_MONTH];"
DoCmd.RunSQL (strSQL)
End If
End Sub
RunSQL is for running action queries like update, insert, select into, delete, etc as per Microsoft definition https://msdn.microsoft.com/en-us/library/office/ff194626.aspx , you should probably use OpenQuery or similar to run your query.
I am executing SQL in VB6 and this is the string that I am using, where I define currFA as a number 1. I've been debugging and working at this since it's using inner joins and unions (it's a query I made in Access that I am trying to put into VB6 to run). Right now, I'm getting an operator missing error on the run.
sql = "SELECT DISTINCT [~ALLCBLEQ].Equipment, [~FIRE_AREAS].INDEX" _
& "FROM ([~FIRE_AREAS] INNER JOIN [~ALLTARGETS] ON [~FIRE_AREAS].FULL_ID = [~ALLTARGETS].FA) INNER JOIN ([~ALLRWCBL] INNER JOIN [~ALLCBLEQ] ON" _
& "[~ALLRWCBL].Cable = [~ALLCBLEQ].Cables) ON [~ALLTARGETS].TARGET = [~ALLRWCBL].Cable" _
& "WHERE ((([~FIRE_AREAS].INDEX) = '" & currFA & "'))" _
& "UNION" _
& "SELECT DISTINCT [~ALLCBLEQ].Equipment, [~FIRE_AREAS].INDEX" _
& "FROM [~FIRE_AREAS] INNER JOIN (([~ALLTARGETS] INNER JOIN [~ALLRWCBL] ON [~ALLTARGETS].TARGET=[~ALLRWCBL].Raceway) INNER JOIN [~ALLCBLEQ] ON" _
& "[~ALLRWCBL].Cable=[~ALLCBLEQ].Cables) ON [~FIRE_AREAS].FULL_ID=[~ALLTARGETS].FA" _
& "WHERE ((([~FIRE_AREAS].INDEX) = '" & currFA & "'));"
Any help on the error and syntax improvement tips are greatly appreciated! Still learning!
Thanks!
Your string has no spaces between the lines so when you write:
sql = "SELECT DISTINCT [~ALLCBLEQ].Equipment, [~FIRE_AREAS].INDEX" _
& "FROM ([~FIRE_AREAS] …
That becomes a SQL string like
SELECT DISTINCT [~ALLCBLEQ].Equipment, [~FIRE_AREAS].INDEXFROM ([~FIRE_AREAS] …
Which is obviously invalid SQL because there's no space between INDEX and FROM.
An easy solution is just to put a space before each closing quote (or after each open quote):
sql = "SELECT DISTINCT [~ALLCBLEQ].Equipment, [~FIRE_AREAS].INDEX " _
& "FROM ([~FIRE_AREAS] …
However, If you find yourself writing relatively complex queries like this, I would recommend that you consider converting them to stored procedures or views instead.
I am looking to update one of my tables with another table depending on a field condition. I am wondering what the correct way to do this is. I tried to do UPDATE statements with the 2 tables, but everytime it came out with this error: Too few Parameters, Expected 2
My goal:
If SOURCING field = O, I want Zip Code to be Origin Postal Code
If SOURCING field = D, I want Zip Code to be Dest Postal Code
So as of right now, I am simply doing a LEFT JOIN with a condition. Is this the best way to do it? Or should I have done this with the original INSERT statement somehow?
CurrentDb.Execute "UPDATE Processing" & _
" LEFT JOIN tblImport" & _
" ON Processing.[BATCH_NO] = tblImport.[BATCH_NO]" & _
" SET Processing.[Zip Code] = tblImport.[Origin Postal Code]" & _
" WHERE tblImport.[Sourcing] = O;"
CurrentDb.Execute "UPDATE Processing" & _
" LEFT JOIN tblImport" & _
" ON Processing.[BATCH_NO] = tblImport.[BATCH_NO]" & _
" SET Processing.[Zip Code] = tblImport.[Dest Postal Code]" & _
" WHERE tblImport.[Sourcing] = D;"
I have tried changing the WHERE statement since I am not sure if it should be in quotes, single quotes, not in quotes, etc... but I have come up empty there. Everything else looks correct to me.
Here's what I do, you might find this helpful; Set a variable equal to your SQL string, then CurrentDB.Execute the variable. Why is this helpful? Because you can break the code after the variable is set, and then copy the SQL into a new query and see what it's complaining about. :o)
Dim tmpUpdate as string
tmpUpdate = "UPDATE Processing" & _
" LEFT JOIN tblImport" & _
" ON Processing.[BATCH_NO] = tblImport.[BATCH_NO]" & _
" SET Processing.[Zip Code] = tblImport.[Origin Postal Code]" & _
" WHERE tblImport.[Sourcing] = O;"
CurrentDB.Execute tmpUpdate
Set a breakpoint on the "tmpUpdate =" line, and then run the code. When it hits the breakpoint, press F8 to step to the next line. In the Immediate window, type "?tmpUpdate" (without the quotes) and see what it thinks the variable is equal to. Then, go to the database, create a new query and go to the SQL of the query. Copy and paste the SQL from the Immediate window and try running the query. If it pukes, go to the Design view and see if you can see anything that doesn't look right.
I write you this time because a VBScript that one of the application my company uses to retrieve information from an Oracle database does not seem to be working properly. Here are the facts:
There's part of the code that does the following:
sSql = "SELECT REQ_PAYMODE" & _
" FROM SYSADM.GBPRESTATIEGROEP" & _
" WHERE 1=1" & _
" AND SLEUTEL = " & sKeyPrestatiegroep
Set oRSGBPrest = connADO.execute(sSql)
If Not oRSGBPrest.EOF Then
sRequestPaymodeKey = oRSGBPrest("REQ_PAYMODE")
Else
//error handling
End If
Using a Statement Tracer for Oracle (www.aboves.com) I can capture that same statement with its corresponding value:
SELECT REQ_PAYMODE FROM
SYSADM.GBPRESTATIEGROEP WHERE 1=1 AND
SLEUTEL = 1572499
Now, the VBScript is supposed to take that value and execute another query:
sSql = "SELECT PAM_CODE" & _
" FROM SYSADM.PAYMODES" & _
" WHERE 1=1" & _
" AND PAM_KEY = " & sRequestPaymodeKey
Set oRSPaymodes = connADO.execute(sSql)
Right in this last line of code, the script throws an error that says:
ORA-00936: missing expression at line XXX --> Set oRSPaymodes = connADO.execute(sSql) <--
Which basically means that the query in (3) is not correct, which also means that for some reason sRequestPaymodeKey is empty. I cannot tell this for sure because this failing sql statement does not appear in the statement tracer, but that's the only explanation I could find. However, the worst part is that when running the query (2) on SQLDeveloper (that's where value sRequestPaymodeKey comes from) it shows a row with a value other than null or zero.
I can't think of anything else that might be happening here, maybe it's just a server thing... no idea.
Any suggestions from you guys? Any way I can actually debug a VBE file?
Your help is much appreciated!
You need to cast sRequestPaymodeKey as a vbLong which corresponds to sql's INT. I'm assuming PAM_KEY is an INT. A recordset will return a string value. So, your code would look like this:
If IsNumeric(sRequestPaymodeKey) Then
sSql = "SELECT PAM_CODE" & _
" FROM SYSADM.PAYMODES" & _
" WHERE 1=1" & _
" AND PAM_KEY = " & CLng(sRequestPaymodeKey)
Set oRSPaymodes = connADO.execute(sSql)
Else
'do error handling due to bad returned data(empty string?)
End If
Also, consider parameterizing your queries to prevent sql injection.
A few ideas to try:
Before Set oRSPaymodes = connADO.execute(sSql), put in a MsbBox and see what SQL is being executed. Is it valid? Will it run in a Oracle query analyzer(if there is one)?
Hard code a valid value in place of sRequestPaymodeKey. Does it work then?