Operator/Syntax Error - sql

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.

Related

SQL Server Join Tables By Combining 2 Columns

This sounds ridiculously easy but I've tried so many different approaches. This query is just set up weird and I'm trying to JOIN it but there's not a common column I can do that with. There is, however, a LastFirst column (consists of LastName then FirstName) written in the context of DOE, JOHN. Then on the columns I'm trying to join that with it's just FirstName (John) and LastName (Doe).
I'm actually trying to select data from 4 tables that all are returning 1 row. These 2 tables can be joined:
SELECT
RIFQuery.*,
_Employee.EmployeeLastName + ', ' + _Employee.EmployeeFirstName AS EmployeeLastFirst,
_Employee.EmployeeTitle, _Employee.Phone As EmployeePhone,
_Employee.EmailAddress As EmployeeEmailAddress
FROM
RIFQuery
INNER JOIN
_Employee ON RIFQuery.CreatedBy = _Employee.AutoNumber
WHERE
RIFQuery.Autonumber = 1
This one has nothing to join with so I'll probably union it and null remaining columns:
SELECT *
FROM tblOrganization
This is the table that contains LastName and FirstName that I'm trying to join with RIFQuery.LastFirst:
SELECT
Gender As ClientGender, DOB As ClientDOB, SSN As ClientSSN
FROM
_Clients
WHERE
_Clients.LASTNAME = left(RIFQuery.LastFirst, len(RIFQuery.LastFirst)-CHARINDEX(',', REVERSE(RIFQuery.LastFirst)))
AND _Clients.FIRSTNAME = ltrim(substring(RIFQuery.LastFirst, len(RIFQuery.LastFirst)-CHARINDEX(',', REVERSE(RIFQuery.LastFirst))+2, len(RIFQuery.LastFirst)))
In that WHERE statement the code will split the LastFirst column and get the row by searching their LastName and FirstName. I'm wondering if there's a way I can write that into a JOIN? Otherwise I can probably UNION and null remaining columns but it will look very ugly.
UPDATE
I tried 2 suggestions from here and both result in a syntax error. I forgot to mention that I'm executing this code inside Microsoft Access VBA and trying to retrieve a DAO.RecordSet. I had to remove some table names in the SELECT statement to get past a syntax error from there, so maybe I should update the question to reflect MS ACCESS and not SQL Server, although only the query is the only pure Access object and the rest are linked ODBC tables to SQL Server.
UPDATE
Just one of those issues where I can't sleep until it's fixed and will obsess until it is. If I take out all _Employee references (from SELECT and JOIN statements), it wants to work but errors about too few parameters. I just now know this is related to _Employee. Getting different results from applying parentheses and just hoping I'll get lucky and hit on it.
The error is caused by this line:
INNER JOIN [_Employee] ON [_Employee].[AutoNumber] = [RIFQuery].[CreatedBy]
I get this error:
"Syntax error (missing operator) in query expression".
As seen in this screenshot:
Here's my latest query I'm playing with, minus the parentheses:
str = "SELECT [RIFQuery].*, " & vbCrLf & _
" ([_Employee].[EmployeeLastName] & ', ' & [_Employee].[EmployeeFirstName]) AS [EmployeeLastFirst], " & vbCrLf & _
" [_Employee].[EmployeeTitle], " & vbCrLf & _
" [_Employee].[Phone] AS [EmployeePhone], " & vbCrLf & _
" [_Employee].[EmailAddress] AS [EmployeeEmailAddress], " & vbCrLf & _
" [_Clients].[Gender] AS [ClientGender], " & vbCrLf & _
" [_Clients].[DOB] AS [ClientDOB], " & vbCrLf & _
" [_Clients].[SSN] AS [ClientSSN] " & vbCrLf & _
"FROM [_Clients] " & vbCrLf & _
" INNER JOIN [RIFQuery] ON [RIFQuery].[LastFirst] = [_Clients].[LASTNAME] & ', ' & [_Clients].[FIRSTNAME] " & vbCrLf & _
" INNER JOIN [_Employee] ON [_Employee].[AutoNumber] = [RIFQuery].[CreatedBy] " & vbCrLf & _
"WHERE [RIFQuery].[Autonumber] = 1;"
For debugging purposes, if I remove those last 2 lines and the _Employee SELECT statements, it'll process the query without a problem. If anyone has any ideas just let me know.
I was focused on that RIFQuery JOIN statement being the culprit for the longest time but I've found that simply is not the issue any more. With that said, this thread has been essentially solved and I appreciate the help.
MS Access is using a slightly different syntax than SQL Server when it comes to using more than one JOIN. You could leave out the JOIN with the _Clients (making it a cross join) and move that condition to the WHERE clause, which would make the query look like this (and which would allow you to display the design window for the query without any problem)
SELECT RIFQuery.*,
EmployeeLastName + ', ' + EmployeeFirstName As EmployeeLastFirst,
EmployeeTitle, Phone As EmployeePhone, EmailAddress As EmployeeEmailAddress,
Gender As ClientGender, DOB As ClientDOB, SSN As ClientSSN
FROM _Clients, RIFQuery INNER JOIN _Employee ON RIFQuery.CreatedBy = _Employee.AutoNumber
WHERE RIFQuery.LastFirst = _Clients.LASTNAME & ", " & _Clients.FIRSTNAME;
Instead of assembling the query string in VBA just for being able to change the parameter value, I suggest to save the following query as an Access object (maybe qryRIF):
PARAMETERS lgRIF Long;
SELECT RIFQuery.*,
EmployeeLastName + ', ' + EmployeeFirstName As EmployeeLastFirst,
EmployeeTitle, Phone As EmployeePhone, EmailAddress As EmployeeEmailAddress,
Gender As ClientGender, DOB As ClientDOB, SSN As ClientSSN
FROM _Clients, RIFQuery INNER JOIN _Employee ON RIFQuery.CreatedBy = _Employee.AutoNumber
WHERE RIFQuery.LastFirst = _Clients.LASTNAME & ", " & _Clients.FIRSTNAME
AND RIFQuery.Autonumber = [lgRIF];
In your VBA code, you can use code like the following to grab the QueryDef object, assign the parameter value and open a recordset:
With CurrentDb.QueryDefs!qryRIF
!lgRIF = lgRIF
With .OpenRecordset()
' ... your code ...
.Close
End With
.Close
End With

Access VBA 'Syntax Error in Join Operation'

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.

MS Access Inner Join - Concatenation in the ON clause

Working code sample for SQL SERVER
Select Top 1 bc.Tier_Name, bc.Unit_ID, bc.Name, bc.Description_2
FROM bc_subs as bc INNER JOIN Product_V as v
ON v.ABC = 'ABC: ' + bc.Unit_ID
Problem code sample for Access SQL VBA
"Select Top 1 bc.Tier_Name, bc.Unit_ID, bc.Name, bc.Description_2 " & _
"FROM bc_subs as bc INNER JOIN Product_V as v" & _
"ON v.ABC = " & "ABC: " & "bc.Unit_ID "
In Access, I am trying to INNER JOIN to a table, but part of the join has to concat a string to the front of the value. Table V's key is ABC:123, but the key in BC is just 123 -- so I have to add the ABC: to the font of the 123 to make both sides equal to ABC:123.
I have tried several variations on the VBA Access SQL string but cannot seem to get the join to work correctly.
Any advice? The code was truncated and edited out, variables and alias names changed for safety type reasons. It is the logic I am after within the VBA code and the assignment of a string to a value like this.
You miss a space and some quoting:
"bc.Tier_Name, bc.Unit_ID, bc.Name, bc.Description_2 " & _
"FROM bc_subs as bc INNER JOIN Product_V as v " & _
"ON v.ABC = 'ABC:' + bc.Unit_ID"
The quotes you're using to concatenate, break your string. You can use double quotes to escape them, and get what's functionally equivalent to your SQL server query.
Also, queries using a join with a constant in the on clause in Access should have the on clause surrounded by parentheses to avoid errors in some conditions. I recommend always using them, to be safe.
"Select bc.Tier_Name, bc.Unit_ID, bc.Name, bc.Description_2 " & _
"FROM bc_subs as bc INNER JOIN Product_V as v " & _
"ON (v.ABC = ""ABC: "" & bc.Unit_ID) "
Alternatively, you can write this as a CROSS JOIN:
"Select bc.Tier_Name, bc.Unit_ID, bc.Name, bc.Description_2 " & _
"FROM bc_subs as bc, Product_V as v " & _
"WHERE (v.ABC = ""ABC: "" & bc.Unit_ID) "

Troubles with joining tables in Excel VBA

I'm trying to take a crystal report sql and convert it so I can use it in excel. I'm having troubles with the syntax of the joining statements in Excel. I can do a couple of tables individually, but cant combine them.
From crystal reports: What I'm trying to copy:
SELECT "Material_Req"."Job", "Material_Req"."Pick_Buy_Indicator", "Material_Req"."Material", "Material_Req"."Description", "Material_Req"."Vendor_Reference", "PO_Detail"."PO", "Material_Req"."Est_Qty", "Source"."Act_Qty", "PO_Header"."Vendor", "PO_Detail"."Due_Date"
FROM (("PRODUCTION"."dbo"."Material_Req" "Material_Req" LEFT OUTER JOIN "PRODUCTION"."dbo"."Source" "Source" ON "Material_Req"."Material_Req"="Source"."Material_Req") LEFT OUTER JOIN "PRODUCTION"."dbo"."PO_Detail" "PO_Detail" ON "Source"."PO_Detail"="PO_Detail"."PO_Detail") LEFT OUTER JOIN "PRODUCTION"."dbo"."PO_Header" "PO_Header" ON "PO_Detail"."PO"="PO_Header"."PO"
WHERE "Material_Req"."Pick_Buy_Indicator"='b' AND "Material_Req"."Est_Qty">"Source"."Act_Qty"
ORDER BY "Material_Req"."Job"
Previous one that worked:
sqlMatlReq = "select job.job, material_req.vendor_reference, material_req.Material,'' As Description, material_req.Vendor," _
& "(material_req.est_qty) As Qty, (material_req.act_qty) As Qty, " _
& "material_req.due_date, " _
& " material_req.status " _
& "from (material_req inner join job on material_req.job=job.job) " _
& "left join material on material_req.material=material.material " _
& "where material.material is not null " _
& "and job.part_number is not null " _
& "and Job.Status in('Active') " _
& "and material_req.act_qty in('0') " _
& "Union all " _
& "select job.job, material_req.vendor_reference, material_req.Material, material_req.description, material_req.Vendor," _
& "(material_req.est_qty), (material_req.act_qty) As Qty," _
& " material_req.due_date, material_req.status " _
& "from (material_req inner join job on material_req.job=job.job) " _
& "left join material on material_req.material=material.material " _
& "where material.material is null " _
& "and job.part_number is not null " _
& "and Job.Status in('Active') " _
& "and material_req.act_qty in('0') " _
& "order by job.job;"
As far as I got: having troubles combining the three
'sqlMatlReq = "select job.job, material_req.material, material_req.Vendor_Reference, material_req.description, material_req.Est_Qty " _
'& "from (material_req inner join job on material_req.job=job.job) " _
'sqlMatlReq = "select source.Act_Qty, PO_Detail.PO, PO_Detail.Due_Date " _
'& "from source left outer join PO_Detail on source.Act_qty=PO_Detail.PO_Detail "
'sqlMatlReq = "select PO_Header.vendor " _
'& "from PO_Header"
Thanks in advance.
SQL Server Stored Procedures for Use With Crystal Reports
CREATE PROCEDURE sp_SampleProcedure
AS
BEGIN
SET NOCOUNT ON;
SELECT table_catalog, table_schema, table_name, table_type
FROM tbldm.information_schema.tables
WHERE table_schema = 'dbo'
AND table_type = 'BASE TABLE';
END;
Where any query you would like to see supplying data to the Crystal Reports client should be represented by the last SELECT statement issued in the SQL Server STORED procedure. This example points to the SQL data dictionary of Table Names and Types.
Define a DSN connection between the Crystal Reports client and the SQL Database Server. There may already be one of other reports were designed before this.
Stored procedures should show up in its schema catalog alongside the other objects typically found by the Crystal report writer when selecting db objects to use.
Note, procedures can be parametrized and their input variables used throughout the procedure itself.

Join operation syntax error

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.