Updating Access Database using UPDATE SQL statement in VBA - sql

Can someone take a look a the stSQL string and help me fix the syntax error I am getting associated with the UPDATE statement?
Run-time error '-2147217900 (8004e14)': Syntax error in UPDATE statement.
I have a rudimentary understanding of SQL and don't seem to understand where I have gone wrong.
I want to update the fields of Table 1 if the FileName UserForm value matches a FileName field in the Access Db.
Thanks
Public Sub UpdateDatabaseEntry()
Dim cn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim stDB As String, stSQL As String, stProvider As String
Dim FileName As String
Dim Nickname As String
Dim RecipientName As String
Dim RecipientRelationship As String
Dim Summary As String
Dim Noteworthy As String
Dim PreparedBy As String
FileName = UserForm1.FileNameTextBox.Text
Nickname = UserForm1.NicknameTextBox.Text
RecipientName = UserForm1.RecipientNameTextBox.Text
RecipientRelationship = UserForm1.RecipientRelationshipComboBox.Text
Summary = UserForm1.SummaryTextBox.Text
Noteworthy = UserForm1.NoteworthyCheckBox.Value
PreparedBy = UserForm1.PreparedByTextBox.Text
stDB = "Data Source= E:\MyDb.accdb"
stProvider = "Microsoft.ACE.OLEDB.12.0"
//Opening connection to database
With cn
.ConnectionString = stDB
.Provider = stProvider
.Open
End With
//SQL Statement telling database what to do
stSQL = "UPDATE Table1" & _
"SET Nickname= '" & Nickname & "', RecipientName= '" & RecipientName & "', " & _
"RecipientRelationship= '" & RecipientRelationship & "', Summary= '" & Summary & "', " & _
"Noteworthy= '" & Noteworthy & "', PreparedBy= '" & PreparedBy & "', " & _
"WHERE FileName= '" & FileName & "'"
cn.Execute stSQL
cn.Close
Set rs = Nothing
Set cn = Nothing
End Sub

At least one problem is caused by lack of spaces in the query. So your query started UPDATE Table1set.
stSQL = "UPDATE Table1 " & _
"SET Nickname= '" & Nickname & "', RecipientName= '" & RecipientName & "', " & _
"RecipientRelationship= '" & RecipientRelationship & "', Summary= '" & Summary & "', " & _
"Noteworthy= '" & Noteworthy & "', PreparedBy= '" & PreparedBy & "'" & _
"WHERE FileName= '" & FileName & "'"
If this doesn't fix the problem. Then edit your question with the value of stSQL after the variable substitution.
EDIT:
As TS points out, another problem is the , before the where (fixed above).

Related

UPDATE Query in MS Access using SQL in VBA with declared strings

been a while since I've posted so please forgive any formatting issues. Looking to update a table field with a value from another record in the same field in the same table.
I've declared two strings, and the strDeal string is coming back with the correct values when debugging. However when I introduce the string into the sql statement I can't the query to update the field. I'm not sure exactly what isn't working correctly, so any help would be appreciated.
The basics are I'm trying to update the Case_Qty field with a value from the same field in the same table based on the returned value from a subquery. Thanks!
Dim strDeal As String
Dim strSQL As String
strDeal = DMax("[Deal_No]", "[tblStructuresNoDAworking]", "[Structure_Name] = Forms!frmStructNoDASetup!Structure_Name AND [FG_Ind] = 0 AND [Deal_No] < Forms!frmStructNoDASetup!Deal_No")
strSQL = "UPDATE tblStructuresNoDAworking SET tblStructuresNoDAworking.Case_Qty = (SELECT [Case_Qty] FROM tblStructuresNoDAworking WHERE [Structure_Name] = '" & Me.Structure_Name.Value & "' AND [Deal_No] = '" & strDeal & "') WHERE [Structure_Name] = '" & Me.Structure_Name.Value & "' AND [Deal_No] = '" & Me.Deal_No.Value & "'"
DoCmd.RunSQL (strSQL)
Try this where you concatenate the values from the form:
Dim strDeal As String
Dim strSQL As String
strDeal = DMax("[Deal_No]", "[tblStructuresNoDAworking]", "[Structure_Name] = '" & Forms!frmStructNoDASetup!Structure_Name & "' AND [FG_Ind] = 0 AND [Deal_No] < '" & Forms!frmStructNoDASetup!Deal_No & "'")
strSQL = "UPDATE tblStructuresNoDAworking " & _
"SET tblStructuresNoDAworking.Case_Qty = " & _
" (SELECT [Case_Qty] " & _
" FROM tblStructuresNoDAworking " & _
" WHERE [Structure_Name] = '" & Me.Structure_Name.Value & "' AND [Deal_No] = '" & strDeal & "') " & _
"WHERE [Structure_Name] = '" & Me.Structure_Name.Value & "' AND [Deal_No] = '" & Me.Deal_No.Value & "'"
DoCmd.RunSQL strSQL
For numeric Deal:
Dim Deal As Long
Dim strSQL As String
Deal = DMax("[Deal_No]", "[tblStructuresNoDAworking]", "[Structure_Name] = '" & Forms!frmStructNoDASetup!Structure_Name & "' AND [FG_Ind] = 0 AND [Deal_No] < '" & Forms!frmStructNoDASetup!Deal_No & "'")
strSQL = "UPDATE tblStructuresNoDAworking " & _
"SET tblStructuresNoDAworking.Case_Qty = " & _
" (SELECT [Case_Qty] " & _
" FROM tblStructuresNoDAworking " & _
" WHERE [Structure_Name] = '" & Me.Structure_Name.Value & "' AND [Deal_No] = " & Deal & ") " & _
"WHERE [Structure_Name] = '" & Me.Structure_Name.Value & "' AND [Deal_No] = " & Me.Deal_No.Value & ""
DoCmd.RunSQL strSQL

Increase speed of multiple inserts into Access DB from VBA Dictionary

I am attempting to take a VBA Dictionary and either:
Insert a new row into the database if it does not exist
Update the row if it does
While my current code works for this, it runs extremely slowly for the thousands of records I may need to update, and other solutions I have found on this site do not really achieve what I am after. Could anyone help me achieve this? My code so far is below:
Sub UpdateDatabase(dict As Object)
Dim Conn As Object, StrSQL As String, Rs As Object
Dim hmm As ADODB.Recordset
Set Conn = CreateObject("ADODB.Connection")
Conn.Provider = "Microsoft.ACE.OLEDB.12.0"
Conn.Open "C:\XXXX\cfrv2.accdb"
dictCount = dict.Count
counter = 0
For Each varKey In dict.Keys()
Application.StatusBar = Str(counter) & "/" & Str(dictCount)
counter = counter + 1
StrSQL = "SELECT * FROM `All SAMs Backlog` WHERE [LOCID] = '" & varKey & "'"
Set hmm = Conn.Execute(StrSQL)
If hmm.BOF And hmm.EOF Then
StrSQL = "INSERT INTO `ALL SAMs Backlog` ([SAM], [LOCID], [RTC Date], [CFR Status], [CFR Completed Date], [CFR On Hold Reason], [MDU], [ICWB Issue], [Obsolete]) VALUES (dict.Item(varKey)(0), '" & varKey & "', '20/12/2018', '" & dict.Item(varKey)(1) & "', '02/01/2019', '" & dict.Item(varKey)(2) & "' , '" & dict.Item(varKey)(3) & "' , '" &dict.Item(varKey)(4) & "' , '" & dict.Item(varKey)(5) & "')"
Conn.Execute (StrSQL)
Else
'Update the LOC in the table
StrSQL = "UPDATE `All SAMs Backlog` SET ([CFR Status] = '" & dict.Item(varKey)(1) & "', [CFR On Hold Reason] = '" & dict.Item(varKey)(2) & "', [MDU] = '" & dict.Item(varKey)(3) & "', [ICWB Issue] = '" & dict.Item(varKey)(4) & "', [Obsolete] = '" & dict.Item(varKey)(5) & "')"
Conn.Execute (StrSQL)
End If
Next
Conn.Close
End Sub
Any help is appreciated.
Either:
Write the content of the dictionary to a temp table, then run a query as described here:
Update or insert data in table
or:
Open [All SAMs Backlog] as a recordset, loop the dictionary to add or edit records as needed, then close the recordset.

VBA + SQL Server - Get Last ID Inserted

Hope you can help - I'm having issues getting the last ID after INSERT.
So the environment - Access 2016, SQL Server and VBA
Dim db As DAO.Database
Dim RS As New ADODB.Recordset
Dim sql As String
I have theses declared and then private sub.
Private Sub CreateOrderHeader()
Dim CustomerID As Integer
Dim OrderDate As String
Dim OrderStatus As String
Dim OrderValue As Double
Dim OrderNotes As String
Dim OrderPostageID As String
Dim OrderAddressID As String
Dim OrderBatchID As Integer
Dim OrderPayment As String
Dim OrderCourierID As String
Dim OrderAgentID As Integer
Dim OrderOutstanding As Double
CustomerID = tbxCusID
OrderDate = Format(Now)
OrderStatus = "InProcess"
OrderValue = txtTotal.value
OrderNotes = tbxNotes.value
OrderPostageID = txtPostage.Column(0)
If tbxCustomerAddress = tbxDeliveryAddress Then
OrderAddressID = 3 'default customers address
Else
'NEED TO GET CUSTOMER ADDRESS TO DO
End If
OrderBatchID = cmbBatch.Column(0)
OrderPayment = sPayMethod
OrderCourierID = cbxShipping.Column(0)
OrderAgentID = 0
OrderOutstanding = txtTotal.value
Dim testvar As String
sql = "INSERT INTO dbo_OrderHeader " _
& "(OrdCusID, OrdDate, OrdStatus, OrdValue, OrdNotes, OrdPostageID, OrdDelAddID,OrdBatchID,OrdPaymentMethod, OrdCourierID,ordAgentID, OrdOutstanding,OrdSource) " _
& " VALUES ('" & CustomerID & "' ,'" & OrderDate & "', '" & OrderStatus & "', '" & OrderValue & "', '" & OrderNotes & "', '" & OrderPostageID & "','" & OrderAddressID & "','" & OrderBatchID & "','" & OrderPayment & "','" & OrderCourierID & "','" & OrderAgentID & "','" & OrderOutstanding & "', 1)"
DoCmd.RunSQL (sql)
sql = "SELECT ##IDENTITY As IDT"
RS.Open sql, CurrentProject.Connection, adOpenStatic, adLockReadOnly
IDT = RS!IDT
MsgBox ("Succes - OrderHeader" & " '" & IDT & "' ")
End Sub
I was expecting a result from this code:
sql = "SELECT ##IDENTITY As IDT"
RS.Open sql, CurrentProject.Connection, adOpenStatic, adLockReadOnly
IDT = RS!IDT
But that gives me "0" as result.
Can you help please.
Thanks
You can try this :
Set db = CurrentDB
db.Execute(sql)
IDT = db.OpenRecordset("SELECT ##IDENTITY")(0)
Set db = Nothing
NOTE
Don't execute your insert query like DoCmd.RunSQL (sql) Instead follow the above approach.

syntax error on edit button vb.net [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Here is the code for my edit command. When I click the edit button message, a syntax error on the update statement pop up. But when debugging, there was no error.
Try
Dim SqlQuery As String = "UPDATE data SET archivedate = '" & txtarcdate.Text & "', filenumber = '" & txtfilenum.Text & "', filedate = '" & txtfiled.Text & "', section ='" & txtsection.Text & "', subject '" & txtsubject.Text & "' WHERE number = " & number & ";"
Dim SqlCommand As New OleDbCommand
With SqlCommand
.CommandText = SqlQuery
.Connection = conn
.ExecuteNonQuery()
End With
MsgBox("One record successfully updated.")
loadListView()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Here is your query statement:
Dim SqlQuery As String = "UPDATE data SET archivedate = '" & txtarcdate.Text & "', filenumber = '" & txtfilenum.Text & "', filedate = '" & txtfiled.Text & "', section ='" & txtsection.Text & "', subject '" & txtsubject.Text & "' WHERE number = " & number & ";"
Lets pay attention on this part:
& "', subject '" & txtsubject.Text &
You missed the equals sign. Should be:
& "', subject = '" & txtsubject.Text &
So the complete line would be:
Dim SqlQuery As String = "UPDATE data SET archivedate = '" & txtarcdate.Text & "', filenumber = '" & txtfilenum.Text & "', filedate = '" & txtfiled.Text & "', section ='" & txtsection.Text & "', subject = '" & txtsubject.Text & "' WHERE number = " & number & ";"
And finally, research about SQL injection. It is a serious security problem that your code are suffering.

Unclosed Quotation mark after the character string 'test'

I have been racking my brain with searching on the internet for the solution, but to no avail, I have been unsuccessful.
strSQL = "Update tTbl_LoginPermissions SET LoginName = '" & StrUserName & "', PWD = '" & StrPWD & "', fldPWDDate = '" & Now() & "'" & _
"WHERE intLoginPermUserID = " & MyMSIDColumn0
Once I get the error out, I would like to actually use this where clause:
'WHERE intLoginPermUserID IN (SELECT intCPIIUserID From vw_ADMIN_Frm_LoginBuilder)
Here is the entire code:
Dim con As ADODB.Connection
Dim cmd As ADODB.Command
Dim strSQL As String
Const cSQLConn = "DRIVER=SQL Server;SERVER=dbswd0027;UID=Mickey01;PWD=Mouse02;DATABASE=Regulatory;"
Dim StrUserName As String, StrPWD As String
'passing variables
StrUserName = FindUserName()
StrPWD = EncryptKey(Me.TxtConPWD)
'Declaring the SQL expression to be executed by the server
strSQL = "Update tTbl_LoginPermissions SET LoginName = '" & StrUserName & "', PWD = '" & StrPWD & "', fldPWDDate = '" & Now() & "#" & _
"WHERE intLoginPermUserID = " & MyMSIDColumn0
'WHERE intLoginPermUserID = ANY (SELECT intCPIIUserID From vw_ADMIN_Frm_LoginBuilder)
Debug.Print strSQL
'connect to SQL Server
Set con = New ADODB.Connection
With con
.ConnectionString = cSQLConn
.Open
End With
'write back
Set cmd = New ADODB.Command
With cmd
.ActiveConnection = con
.CommandText = strSQL
.CommandType = adCmdText
.Execute
Debug.Print strSQL
End With
'close connections
con.Close
Set cmd = Nothing
Set con = Nothing
MsgBox "You password has been set", vbInformation + vbOKOnly, "New Password"
NEWEST CODE Producing Error:
'/Declaring the SQL expression to be executed by the server
strSQL = "Update dbo_tTbl_LoginPermissions " _
& "SET LoginName = '" & StrUserName & "' " _
& "SET PWD = '" & StrPWD & "' " _
& "SET fldPWDDate = '" & Now() & "' " _
& "WHERE intLoginPermUserID = 3;"
I have gone to this site to try to figure out my mistake, but I still cannot figure it out:
After much dilberation and help, it turns out the FindUserName that utilizes a Win32API function was not trimming the Username appropriately.
I changed it to the following:
Public Function FindUserName() As String
' This procedure uses the Win32API function GetUserName
' to return the name of the user currently logged on to
' this machine. The Declare statement for the API function
' is located in the Declarations section of this module.
Dim strBuffer As String
Dim lngSize As Long
strBuffer = Space$(255)
lngSize = Len(strBuffer)
If GetUserName(strBuffer, lngSize) = 1 Then
FindUserName = Left$(strBuffer, lngSize - 1)
Else
FindUserName = "User Name not available"
End If
End Function
Public Declare Function GetUserName Lib "advapi32.dll" Alias "GetUserNameA" (ByVal lpBuffer As String, nSize As Long) As Long
Try this:
strSQL = "Update tTbl_LoginPermissions SET LoginName = '" & replace(StrUserName, "'", "''") & "', PWD = '" & replace(StrPWD, "'", "''") & "', fldPWDDate = '" & Now() & "'" & _
"WHERE intLoginPermUserID = " & MyMSIDColumn0
This was inevitably the code that corrected my (') mystery:
'/passing variables
StrUserName = FindUserName()
StrPWD = EncryptKey(Me.TxtConPWD)
StrUserId = Me.CboUser.Column(0)
'/Declaring the SQL expression to be executed by the server
strSQL = "Update tTbl_LoginPermissions SET " _
& "LoginName = '" & StrUserName & "' , " _
& "PWD = '" & StrPWD & "' ," _
& "fldPWDDate = '" & Now() & "' " _
& "WHERE intLoginPermUserID = '" & StrUserId & "'"