Error in SQL query expression - sql

I´m trying to run the following SQL code on access 2010, but it returns syntax error in query expression. Any ideas what could be causing it?
Thanks in advance.
DELETE FROM Trn_done
WHERE (Trn_done.training =
SELECT Training
FROM Trainings
WHERE (Trainings.Area = '" & Area & "'))

The bracket should be before the nested SQL as mentioned below
DELETE FROM Trn_done
WHERE Trn_done.training IN (
SELECT Training
FROM Trainings
WHERE (Trainings.Area = '" & Area & "')
)

You shouldn't EQUAL a select statement, lest multiple rows in your select cause your code to break. Try this instead:
DELETE td
from Trn_done td
inner join Trainings t
on td.training = t.training
WHERE t.Area = '" & Area & "'

Related

MS Access VBA SQL SELECT * INTO tempTbl WHERE Stuff="" AND OtherStuff BETWEEN Date Range

I have a form with one text box, two combo boxes (dropdowns), and two text boxes with input masks for mm/dd/yyyy 99/99/0000;0;_
I am attempting to use all of these fields as filters for a subform.
I have the controls set to fire after update and run a sub that builds a SELECT * INTO sql string for a temp Table that is then sourceobject'ed back to the subform.
In code I have for each control I have code building a snippet of the Where statement for the final sql. the snippet grows as needed, is labeled "Filter"
Some other non-Finished Code....
If Not IsNull(txtDateFrom) Then
If i > 1 Then Filter = Filter & " AND " & "([Date_LastSaved] >= " & Me.txtDateFrom & ")" & " And " & "([Date_LastSaved] <= " & Me.txtDateTo & ")"
End If
Dim sql As String
sql = "SELECT * INTO tmpTable FROM tblReview"
If Not IsNull(Filter) Then
sql = sql & " WHERE " & Filter
End If
My issue and question is that I am testing this one specific situation where there will be Filter = Filter & " AND " & "DATE_STUFF"
where the final sql looks like...
SELECT * INTO tmpTable FROM tblReview WHERE ReviewStatus = 'Quoted' AND ([Date_LastSaved] >= 09/12/2018) And ([Date_LastSaved] <= 10/16/2018)
which should have some result with the test data. Yet, the tmpTable is empty.
This is only happening when I apply a date range criteria.
I tried BETWEEN but could not nail down the syntax.
Any insight is greatly appreciated, Thanks!
UPDATE:
Answer:
If i > 1 Then Filter = Filter & " AND " & "([Date_LastSaved] >= #" & Me.txtDateFrom & "#)" & " And " & "([Date_LastSaved] <= #" & Me.txtDateTo & "#)"
If you want to use dates then they must be quoted. If you just say 10/16/2018 then you are dividing the integer 10 by 16 by 2018 which will yield an integer zero. It will then convert the dates to an integer to do the compare, which will yield a much bigger number, and thus you get no rows.
Any date testing should always be done using date types rather than strings. I think in msaccess you can surround it in #, but not sure. Just research this.

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

MS Access sql - Update query syntax

Seems a small issue with an sql update query. But I can not get my head around this issue. Not very much acquainted with sql.
Based on a selection, selected rows from a table (7DARphases) are copied and inserted to another table (7tblDAR). And the Project ID (PRJID column) for all the inserted rows should be updated with a fixed value (PID) taken from the form.
Issue is: I am facing syntax issue in the part where the fixed value needs to be inserted in the PRJID column of added rows.
Code is:
Set dbs = CurrentDb
PID = Me.PRJID.Value
sqlstr = "INSERT INTO 7tblDAR (Phase, Deliverable, Link_PIM_temp, Link_PIM_WB, Description, Accept_criteria, Deliv_type, TollgateID, Workstream, Accountable, ClientRACI) SELECT [7DARphases].Phase, [7DARphases].Deliverable, [7DARphases].Link_PIM_temp, [7DARphases].Link_PIM_WB, [7DARphases].Description, [7DARphases].Accept_criteria, [7DARphases].Deliv_type, [7DARphases].TollgateID, [7DARphases].Workstream, [7DARphases].Accountable, [7DARphases].ClientRACI FROM 7DARphases WHERE ((([7DARphases].SolType) Like '*2PP*')) ORDER BY [7DARphases].Phase, [7DARphases].Deliverable;"
sqlUpdt = "update 7tblDAR set PRJID = '" & Me.PRJID.Value & "' from 7tblDAR where tblDAR.PRJID = """""
dbs.Execute sqlstr, dbFailOnError
dbs.Execute sqlUpdt, dbFailOnError
The 'sqlstr' works fine and inserts rows.
But 'sqlUpdt' gives error:
"Run-time error 3075: Syntax error (missing operator) in query expression ..."
Can you please help me out with this.
Plus, if possible, can you suggest to perform this action in one query itself.
Why not put the value in when you insert the values?
sqlstr = "INSERT INTO 7tblDAR (Phase, Deliverable, Link_PIM_temp, Link_PIM_WB, Description, Accept_criteria, Deliv_type, TollgateID, Workstream, Accountable, ClientRACI, PRJID)
SELECT . . .,
'" & Me.PRJID.Value & "'
WHERE [7DARphases].SolType Like '*2PP*')
ORDER BY [7DARphases].Phase, [7DARphases].Deliverable;"
This saves the trouble of having to update it later.

Taking User Input in SQL SELECT TOP query

I need to acquire the sum of the least n number of values from a table
Dim lot As String = "SELECT SUM(x2) AS x3 FROM (SELECT TOP '" & _TextBox2.Text & "' x1 As x2
FROM (
SELECT SharePrice As x1
FROM Shares
WHERE(Company = '" & _TextBox1.Text & "' AND Availability = True)
ORDER BY SharePrice ASC )
)"
I dont have problems witha nything else but the TOP '" & _TextBox2.Text & "' part
Does the SELECT TOP really take parameters in?
I can replace the textbox reference with a hard coded integer and it works. But i want to make it run In visual Basic with user input
You cannot use single quotes around the number in the TOP n portion of the query.
Change:
SELECT TOP '" & _TextBox2.Text & "'
To:
SELECT TOP " & _TextBox2.Text & "
I also recommend that you use a parametrized query to help prevent SQL Injection.
It's a lot easier to do this as a parameterized query. In addition to preventing sql injection attacks it avoids the problems of when to put quotes around things.
In order to get Top to work you will need to surround the parameter name with parens
Dim lot As String = " SELECT SUM(x2) AS x3
FROM
(SELECT TOP (#Top) x1 As x2
FROM (SELECT
SharePrice As x1
FROM Shares
WHERE
(Company = #CompanyName
AND Availability = True)
ORDER BY SharePrice ASC ))"
Dim cmd as SqlCommand = new SqlCommand (connection, lot)
cmd.AddWithValue (#Top, Int32.Parse(_TextBox2.Text))
cmd.AddWithValue (#CompanyName, _TextBox1.Text)

Updating in SQL Problems

Can anyone help me with this problem? I'm trying to update my database using the SQL below, but when I run it this message comes out:
The multi-part identifier "try_subject.subject_code" could not be bound.
UPDATE try_schoolyear
SET school_year= '" & drpcurriculumyear.SelectedItem.Text & "'
FROM try_schoolyear
INNER JOIN try_yearlvl on
try_schoolyear.schoolyearID=try_yearlvl.schoolyearId
WHERE try_subject.subject_code= '" & txtsearchcourse.Text & "'
the table try_subject won't be joined in your query. And that is why the engine can't find it.