Syntax error in Update Statement ASP Classic - sql

I am having the syntax error in my code on a update statement, after reading multiple posts about it I cant figure out what is causing the error.
The code is as follows:
if request.querystring("do")="customer" then
New_customer = request.Form("customer")
openconn con
sSQL="SELECT RelationNumber FROM Relations WHERE RelationName='" & New_customer & "'"
set rst = con.execute(sSQL)
if rst.EOF then
response.write "No relation found"
else
Relationnumber_update = rst("RelationNumber")
sSQL2="SELECT Number FROM Orders WHERE Relation=" & Relationnumber_update & ""
set rst2 = con.execute(sSQL2)
if rst2.EOF then
response.write("No order number found!")
else
if Relationnumber_update <> 1000 then
Ordernumber_update = rst2("Nummer")
sSQL3="UPDATE Bookings SET Order=" & Ordernumber_update & " WHERE ID=" & request("ID")
con.execute(sSQL3)
else
response.write("Order number 1000 is not allowed!")
end if
end if
end if
closeconn con
response.redirect("myPage.asp?action=page")
response.end
end if
The error happens on the line: sSQL3="UPDATE Bookings SET Order=" & Ordernumber_update & " WHERE ID=" & request("ID")
Things to know:
The request queriestring is from the form where the user can choose a customer in a dropdown list. See code: <form name="ChangeCustomer" method="post" action="myPage.asp?action=page&do=customer&ID=<%=rst("ID")%>" style="display:inline">
The rst from ID is from a select statement before which works since I used in also in other code in the same way (that does work).
The openconn con is a function for accessing my database (it works, same reason as above)
Eacht select statement in this code has been tested for its output in a response.write. All the results that came out were the expected ones.
Short description of what happens in the code above
A user changes the customer in the form (with a dropdown menu) and presses save (submit).
On submit the queriestring is launched, this was tested if the code actually comes to this and it does.
The chosen customer is saved in the var New_customer.
The relation number that matches the customer name is retrieved with the first select statement.
The right relation number is being put into the var Relationnumber_update
In the second query the right number is being searched for that equals the relation number.
A if/then follows which makes sure the Relationnumber_update is not equal to 1000 (no updates should be done on this number)
If its not equal to 1000 then the found order number (second select statement) is stored in the var ordernumber_update
The update statement follows where Order field in the bookings table is being updated with the found ordernumber.
In the end (after the if) the connection is being closed and the page is being 'refreshed'.
For some reasson I am getting the syntax error on my update statement but I have no clue why. I checked the data types of the Number field in the orders table, the Relationnumber from the Relations table and the Order field in the bookings table, they are all of type number/int.
I also tried to update with a set number directly in the update statement instead of the ordernumber_update var (like so: sSQL3="UPDATE Bookings SET Order=6477 WHERE ID=" & request("ID")) but this gives the same error..

Three things:
Read about Sql Injections
To debug sql statement "live", use
sSQL3="UPDATE Bookings ...
Response.Write(sSQL3)
'con.execute(sSQL3) -- comment it out
run page, and test resulted sql query against database
If ID has string datatype (char, varchar, etc) then you should quote its value using '...'
P.S.
Use [Order] to deal with reserved words.

Be aware of the reserve words of database management system.
Here you are using Order, which is a reserved one.
So use this if you using MySQL:
sSQL3="UPDATE Bookings SET `Order`=" & Ordernumber_update & " WHERE ID=" & request("ID") &";"
Or in case of SQL Server:
sSQL3="UPDATE Bookings SET [Order]=" & Ordernumber_update & " WHERE ID=" & request("ID") &";"
Hope this will help others also. Thank you.

Use bracketes aound [Order], not single quotes. And don't use reserved words for your field names. Jus sayin'.

Related

Displaying a field associated with a max date value record

I am working on an MS Access database and have been trying to get an unbound field on a main navigation form to display the LastUserChange that is associated with the record that was last updated.
I have used DMax() to identify the record that was most recently updated, but I can't seem to get the user ID associated with that record to display. I have a field in the table with the date timestamp that stores the user ID with it, so the data is saved in the same table. The code that I have been working on is as follows:
Private Sub Form_Load()
Dim strSQL As String
strSQL = "SELECT tblstatusupdate.LastUserChange" & _
"FROM tblstatusupdate " & _
"WHERE tblstatusupdate.LastChangeDate = DMax("LastChangeDate", "tblStatusUpdate")"
DoCmd.RunSQL strSQL
Me.LastUpdateBy = strSQL
End Sub
The code that I used to get the date of the most recently updated record is:
= DMax("LastChangeDate", "tblStatusUpdate")
Can someone please help me?
Often a mistake of new users in MS Access, DoCmd.RunSQL is reserved for action queries (i.e., INSERT, DELETE, UPDATE, ALTER, CREATE) and not SELECT queries that return a resultset.
However, for your needs consider running nested domain functions in VBA without any SQL calls. DLookUp looks up user with the criteria that its change date matches the max value of table using Dmax. Date literals must be enclosed with # characters and not quotes.
Me.LastUpdatedBy = DLookUp("LastUserChange", "tblStatusUpdate", "LastChangeDate = #" _
& DMax("LastChangeDate", "tblStatusUpdate") & "#")

Access delete query not deleting right record

This should not be that hard. I'm simply trying to delete a record from a table, where the ID is equal to a form value. Done it a thousand times.
In this case, the FIRST record in the table is being deleted, NOT the selected one in the form. I've looked at table properties, form properties and tried every delete query variation I'm aware of.
I've tried building a delete query in Query Design and executing that. I've tried a SQL statement by passing the Access query. And I've tried writing the SQL to the Access delete query. All results are the same.
HOWEVER, if I hard code the ID number in the Access Delete Query, the correct record deletes as expected. Here's a few I've tried:
Set dbs = CurrentDb
DoCmd.RunSQL "DELETE * FROM " _
& "tblCourse WHERE coCourseID = " & coCourseID & ";"
Set dbs = CurrentDb
dbs.Execute "DELETE * FROM " _
& "tblCourse WHERE coCourseID = " & coCourseID & ";"
CurrentDb.QueryDefs("dqryDeleteCourse").Sql = "DELETE * FROM tblCourse WHERE
coCourseID = " & coCourseID & ";"
dbs.Execute dqryDeleteCourse
In all cases, the variable IS populating correctly.
Here's the Query Design of the dqry (this does not work):
Field: coCourseID
Table: tblCourse
Delete: WHERE
Criteria: [Forms]![frmCourseEdit]![coCourseID]
(I use this method of Criteria = form object value all throughout this application without an issue)
When Criteria = 1003 (hardcoded), it works.
Any troubleshooting ideas would be most appreciated.

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.

Calculated query on multivalued fields in access

I have a table 'Contacts' which has a multivalued field 'Department'. I have another table 'Outreach' and it has a field 'partner org'. I have a query which combines 'Contacts.Department' and 'outreach.[partner org]' into one field joining the two tables using an outer join on fullname field which is common in both tables.
The SQL statement I have to combine the two fields is
Contacts.Department & ";" & Outreach.[Partner Org] AS [Dept/Partner Org]
If I run this query, I get the error saying
The multivalued field 'Contacts.Department' is not valid in the expression 'Contacts.Department & " " & Outreach.[Partner Org] AS [Dept/Partner Org]'
If I add the '.Value' to the multivalued field, I get multiple rows.
Contacts.Department.Value & " " & Outreach.[Partner Org] AS [Dept/Partner Org]
I want the output to have the multivalued valued field contents followed by a ';' and the partner org name all in the same cell.
Please can someone tell me to how to get this.
Thank You.
I've come up against a similar problem with these useful (from the end-users perspective) but irritating (from the perspective of those analysing) fields.
I came up with a workaround, using a form, that I think solves your problem. I added a pseudo-departments text field to the table, applied slightly modified code from the fourth post to the relevant field(s) "AfterUpdate" events as & when they change (I pass the current record & the SQL string only summarises that record).
Dim db As Database, _
rst As Recordset, _
strSQL As String
Me.Refresh
Set db = CurrentDb
strSQL = "Select PseudoDepartment from YOURTABLE where UNIQUEIDNO = " & Me.UNIQUEIDNO & ";"
Set rst = db.OpenRecordset(strSQL, dbOpenDynaset)
With rst
If .RecordCount > 0 Then
.MoveFirst
.Edit
!PseudoDepartment = MakeList(Me.UNIQUEIDNO)
.Update
End If
End With
To initialise the pseudo-departments field, one could loop through all records one by one to generate the contents. One can then query the data normally and get the results in the form you indicated.
HTH.

dlookup multiple tables and set textbox to result access 2007

I'll try and break down my problem as best I can and explain what I'm trying to achieve. Firstly, I have three tables:
**RFI** (stands for Request For Information)-
Fields: rfi_id, Customer_id .....
**RFI_project** -
Fields: rfipro_id, project_id, rfi_id *"....." represents other unnecessary fields*
**Customer** -
Fields: Customer_id, company .....
I have an access form with two comboboxes. On the first combobox I select the name of a project at which point the second textbox changes to show those *rfi_id*'s where there is a match with the project name selected.
Now what I'm trying to do is this - When I select an *rfi_id* in the second combobox I want it to display in a textbox on my form the company where there the *rfi_id* value matches the value in the combobox. It's a bit tricky due to the way the tables are joined...here is what I'm essentially trying to display in the textbox field in SQL terms:
SELECT Customer.company, RFI.Customer_id
FROM Customer, RFI
WHERE (((Customer.Customer_id)=[RFI].[Customer_id]) AND ((RFI.rfi_id)=[Forms]![Request for Info Form]![Combo90]))
ORDER BY Customer.company;
In order to do this I have tried the following to no avail. In the after update event of my second combobox I have inserted the following:
companyTB = DLookup("company", "Customer", "Customer_id =" & DLookup("Customer_id", "RFI" And "rfi_id =" & [Forms]![Request for Info Form]![cmbRFI]))
When I change the combobox value I get the error Run-time error '13': Type mismatch. I've tried searching for what I've done wrong but this is a very broad error apparently and I can't find anything similar (or that I understand). I also tried this instead -
companyTB = DLookup("company", "Customer", "Customer_id =" & DLookup("Customer_id", "RFI", "rfi_id =" & cmbRFI))
which gives me the following error - Run-time error '3075': Syntax error(missing operator)in query expression. Anyway, would anybody be kind enough to give me a breakdown of what I need to do to achieve this, or what I'm doing wrong (or maybe a better way to do it?). Forgive me for being to seemingly stupid at this, I've only just begun working with access more in depth in the last 3 weeks or so. Thank you.
Your first DLookUp has incorrect syntax:
companyTB = DLookup("company", "Customer", "Customer_id ="
& DLookup("Customer_id", "RFI" And "rfi_id ="
& [Forms]![Request for Info Form]![cmbRFI]))
I have broken it into three lines to make this easier to see. The second line has And between "RFI" and "rfi_id" when it should have a comma.
companyTB = DLookup("company", "Customer", "Customer_id ="
& DLookup("Customer_id", "RFI", "rfi_id =" & cmbRFI))
The error you are getting on your second combo seems likely to be due to the result returned by cmbRFI. You can check this by filling in an actual rfi_id, rather than the reference to the combo and by setting a text box equal to cmbRFI and see what it is returning. Combo can be difficult because the displayed column and the bound column can be different.
It can be convenient to set up your combobox with several columns, as shown in your query, so the rowsource might be:
SELECT rfi.ID, Customer.company, RFI.Customer_id
FROM Customer
INNER JOIN RFI
ON Customer.Customer_id=RFI.Customer_id
ORDER BY Customer.company;
(or the three tables, joined, if necessary)
Then
Column count = 3
Column widths = 2cm;0;0
Bound column = 1
You can now refer to the second column in your textbox:
= cmbRFI.Column(1)
Columns are numbered from zero.
It is always worth reading up on sql before working with Access:
Fundamental Microsoft Jet SQL for Access 2000
Intermediate Microsoft Jet SQL for Access 2000
Advanced Microsoft Jet SQL for Access 2000
Your last Dlookup statement seems absolutely fine so I'm a little confused as to why it isn't working, you may be able to get round the problem like this though:
Combox2_AfterUpdate (Or whatever the event is called)
Dim rs As Recordset
Set rs = Currentdb.OpenRecordset("SELECT C.Company, R.Customer_ID " & _
"FROM Customer As C, RFI As R " & _
"WHERE C.Customer_ID = R.Customer_ID " & _
"AND R.RFI_ID =" & [Forms]![Request for Info Form]![Combo90] & " " & _
"ORDER BY C.Company")
CompanyTB = rs!Company
rs.Close
Set rs = Nothing
End Sub