Update SQL table from VB multiple where condition - sql

I am attempting to update an SQL table from VBA (with the below code)and cant seem to get it correct. I would like to update the columns one, two, three and four based on the search conditions of A, B, C, D, E. What am I getting wrong here? There is no error given, but the table just does not update? thank
Sub UpdateData(A As String, B As String, C As String, D As String, E As String, one As Double, two As Double, three As Double, four As Double)
Dim sA As String, sB As String, sC As String, sD As String, sDesk As String, sE As String
Dim sone As Double, stwo As Double, sthree As Double, sfour As Double
Dim objConn As ADODB.Connection
Set objConn = New ADODB.Connection
objConn.ConnectionString = "Provider=SQLOLEDB;Data Source=source;Initial Catalog=Model_table;Integrated Security=SSPI"
objConn.Open
Set objRec = New ADODB.Recordset
Date = Format(Range("date").Value, "YYYY-MM-DD")
sA = A
sB = B
sC = C
sD = D
sE = E
sone = one
stwo = two
sthree = three
sfour = four
StrSQL = "UPDATE pnl_results SET (" & sone & "," & stwo & "," & sthree & "," & sfour & ") Where ('" & date = sDate & "', '" & AA= sA & _
"','" & BB= sB & "','" CC= & sC & "','" & DD= sD & "','" & EE=sE & ")"
Set objRec = objConn.Execute(StrSQL)
objConn.Close
Set objConn = Nothing
End Sub

There are several errors in your code:
You don't need parentheses.
Put the column names directly in the string, don't surround them with apostrophes.
Surround all string values with apostrophes.
Use AND or OR operator to combine different conditions, not a comma.
Try this:
StrSQL = "UPDATE pnl_results SET " & _
" one = '" & sone & _
"', two = '" & stwo & _
"', three = '" & sthree & _
"', four = '" & sfour & _
"' Where date = '" & sDate & _
"' AND AA = '" & sA & _
"' AND BB = '" & sB & _
"' AND CC = '" & sC & _
"' AND DD = '" & sD & _
"' AND EE = '" & sE & "'"
As mentioned in the comments, using inline query with values coming directly from user input makes your code open to SQL injection attacks. Either validate user input before using it in the query, or better use a parameterized query.

You are confusing the syntax between an Update and an Insert Into. It should look more like this:
StrSQL = "UPDATE pnl_results SET field1='value1', field2='value2' WHERE field3='value3' AND field4='value4'

Related

Is there a better way to write this Access SQL expression?

I have an Access database that I use to track personnel going on trips. When I add someone to a trip, it copies over some information items from the master personnel table into another table that ties that person to the trip and then displays readiness things that I need to track. I'm in the process of updating how the front end talks to the back end in preparation for migrating this over to a proper SQL server rather than just a backend file on a share drive, and was wondering if there was a better way to code this.
Here's the original code:
Dim rst As DAO.Recordset
Set rst = CurrentDb.OpenRecordset("tblMsnPers")
rst.AddNew
rst![MsnID] = Me.ID
rst![EDIPI] = Me.PerSelect
rst![NameStr] = DLookup("[NameStr]", "tblPersonnel", "[EDIPI] = '" & Me.PerSelect & "'")
rst![PriAlt] = Me.cmbPriAlt
rst![Errors] = DLookup("[ScrubErrors]", "tblPersonnel", "[EDIPI] = '" & Me.PerSelect & "'")
rst![PT] = DLookup("[ScrubFitDate]", "tblPersonnel", "[EDIPI] = '" & Me.PerSelect & "'")
rst![vRED] = DLookup("[ScrubvRED]", "tblPersonnel", "[EDIPI] = '" & Me.PerSelect & "'")
rst![ISOPREP] = DLookup("[ISOPREP]", "tblPersonnel", "[EDIPI] = '" & Me.PerSelect & "'")
rst![2760] = DLookup("[Scrub2760]", "tblPersonnel", "[EDIPI] = '" & Me.PerSelect & "'")
rst![Checklist] = DLookup("[ScrubStatus]", "tblPersonnel", "[EDIPI] = '" & Me.PerSelect & "'")
rst![IMR] = DLookup("[ScrubShots]", "tblPersonnel", "[EDIPI] = '" & Me.PerSelect & "'")
rst![Review] = DLookup("[ReviewDate]", "tblPersonnel", "[EDIPI] = '" & Me.PerSelect & "'")
rst.Update
rst.Close
Set rst = Nothing
And here is what my updated code is:
DoCmd.SetWarnings False
SqlStr = "INSERT INTO tblMsnPers " _
& "(MsnID, EDIPI, PriAlt) VALUES " _
& "('" & Me.ID & "', '" & Me.PerSelect & "', '" & Me.cmbPriAlt & "');"
DoCmd.RunSQL SqlStr
SqlStr2 = "UPDATE tblMsnPers INNER JOIN tblPersonnel ON tblMsnPers.EDIPI = tblPersonnel.EDIPI " _
& "SET tblMsnPers.NameStr = [tblPersonnel].[NameStr], " _
& "tblMsnPers.Errors = [tblPersonnel].[ScrubErrors], " _
& "tblMsnPers.PT = [tblPersonnel].[ScrubFitDate], " _
& "tblMsnPers.vRED = [tblPersonnel].[ScrubvRED], " _
& "tblMsnPers.ISOPREP = [tblPersonnel].[ISOPREP], " _
& "tblMsnPers.[2760] = [tblPersonnel].[Scrub2760], " _
& "tblMsnPers.Checklist = [tblPersonnel].[ScrubStatus], " _
& "tblMsnPers.IMR = [tblPersonnel].[ScrubShots], " _
& "tblMsnPers.Review = [tblPersonnel].[ReviewDate], " _
& "tblMsnPers.ATL1 = [tblPersonnel].[ATL1], " _
& "tblMsnPers.SERE = [tblPersonnel].[SERE], " _
& "tblMsnPers.CED = [tblPersonnel].[CED], " _
& "tblMsnPers.GTCexp = [tblPersonnel].[ScrubGTC] " _
& "WHERE ((tblMsnPers.MsnID = " & Me.ID & ") AND (tblMsnPers.EDIPI = '" & Me.PerSelect & "'));"
DoCmd.RunSQL SqlStr2
DoCmd.SetWarnings True
I can't help but feel like there's a better way to write the SQL string here because full disclosure, I have barely half a clue on what I'm doing here, being a student of reverse-engineering and Google-Fu. Is there a better way to write the SQL string here?
I would use this
Dim rstPerson As Recordset
Dim rst As Recordset
Dim strSQL As String
strSQL = "SELECT * from tblersonal where EDIPI = '" & Me.PerSelect & "'"
Set rstPer = CurrentDb.OpenRecordset(strSQL)
Set rst = CurrentDb.OpenRecordset("tblMsnPers")
With rst
.AddNew
!MnID = Me.ID
!EDIPI = Me.PerSelect
!NameStr = rstPer!NameStr
!PriAlt = Me.cmbPriAlt
!Errors = rstPer!ScrubErrors
!PT = rstPer!ScrubFitDate
!vRED = rstPer!ScrubvRED
!ISOPREP = rstPer!ISOPREP
![2760] = rstPer!Scrub2760
!Checklist = rstPer!ScrubStatus
!IMR = rstPer!ScrubShots
!Review = rstPer!ReviewDate
.Update
.Close
End With
This works well since:
All of the data type checking is done for you. (", strings, # dates,
none for numbers)
You don't have messy concatenation.
You get parameter safe code (no sql injection - at least for update part).
It much less code. Far more readable.
And if you convert the data base to sql server, the above code will continue to work.

access 2013 increasing quantity in a table field

Good day. I'm a little stumped about what is happening in my code. I have a userform which collects txtQntyRecd and cboSupplySource. I calculate the lookupValue. And it works just fine. It successfully places the txtQntyRecd in the correct tblWarehouseLocations.WQuantity location. The code is:
updateQnty = "UPDATE tblSupplySources INNER JOIN ((tblWarehouseLocations " & _
"INNER JOIN tblSupplySource_WarehouseLocation ON tblWarehouseLocations.WLocation_ID = tblSupplySource_WarehouseLocation.SWLocation_ID)) " & _
"ON tblSupplySources.SupplySourceID = tblSupplySource_WarehouseLocation.Supply_Source_ID " & _
"SET tblWarehouseLocations.WQuantity = '" & Me.txtQntyRecd & "'" & _
"WHERE (((tblSupplySource_WarehouseLocation.Supply_Source_ID)= " & Me.cboSupplySource & ") " & _
" AND ((tblWarehouseLocations.WLocation_ID)=" & lookupValue & "))"
CurrentDb.Execute updateQnty, dbFailOnError
What I want to do is add the next quantity to the same location. I get weird results if I change the SET statement to the following:
SET tblWarehouseLocations.WQuantity = tblWarehouseLocations.WQuantity + '" & Me.txtQntyRecd & "'"
If I put 200 in the first statement, I get 200 in my WQuantity field. When I change to the second statement and I try to add 1 to the 200 I get a result of 211. If I add 1 again, the result is 223. Add 1 again, the result is 236.
Could someone explain what is happening and why the results aren't 201, 202 and 203? In the future I will need to subtract quantities from WQuantity as well.
Thanks
You're adding quotes around an integer and appending it as a string. Change it to:
".....
SET tblWarehouseLocations.WQuantity = tblWarehouseLocations.WQuantity + " & val(Me!txtQntyRecd) & "....
...."
I've changed the . to a ! as I think it's still a nice distinction between objects properties and controls, and used the val function as it converts the string number value to the integer value.
This is your query in full:
' When I use values from controls, I like to store them in vars
Dim quantityReceived As integer
quantityReceived = val(Me!txtQntyRecd)
updateQnty = "UPDATE tblSupplySources INNER JOIN ((tblWarehouseLocations " & _
"INNER JOIN tblSupplySource_WarehouseLocation ON tblWarehouseLocations.WLocation_ID = tblSupplySource_WarehouseLocation.SWLocation_ID)) " & _
"ON tblSupplySources.SupplySourceID = tblSupplySource_WarehouseLocation.Supply_Source_ID " & _
"SET tblWarehouseLocations.WQuantity = tblWarehouseLocations.WQuantity + " & quantityReceived & _
" WHERE (((tblSupplySource_WarehouseLocation.Supply_Source_ID)= " & Me.cboSupplySource & ") " & _
" AND ((tblWarehouseLocations.WLocation_ID)=" & lookupValue & "))"
I solved the problem. I created a SELECT query to get the present amount in WQuantity. Now quantityReceived = Me!txtQntyRecd + the present amount. With SET tblWarehouseLocations.WQuantity = " & quantityReceived it works fine. However, if just seems so cumbersome.
' lookupValue gives the index into the tblWarehouseLocations where WQuantity resides
Dim lookupValue As Integer
lookupValue = DLookup("[WLocation_ID]", "[tblWarehouseLocations]", "[Location_Name] = '" & Me.cboWLocation & "'")
'Define SQL Query
strSQL = "select tblWarehouseLocations.WQuantity FROM tblWarehouseLocations WHERE (((tblWarehouseLocations.WLocation_ID)= " & lookupValue & "))"
Set rs = db.OpenRecordset(strSQL)
If IsNull(rs!WQuantity) Then
dbvalue = 0
Else
dbvalue = rs!WQuantity
End If
Dim quantityReceived As Integer
quantityReceived = Val(Me!txtQntyRecd) + dbvalue
updateQnty = "UPDATE tblSupplySources INNER JOIN ((tblWarehouseLocations " & _
"INNER JOIN tblSupplySource_WarehouseLocation ON tblWarehouseLocations.WLocation_ID = tblSupplySource_WarehouseLocation.SWLocation_ID)) " & _
"ON tblSupplySources.SupplySourceID = tblSupplySource_WarehouseLocation.Supply_Source_ID " & _
"SET tblWarehouseLocations.WQuantity = " & quantityReceived & _
" WHERE (((tblSupplySource_WarehouseLocation.Supply_Source_ID)= " & Me.cboSupplySource & ") " & _
" AND ((tblWarehouseLocations.WLocation_ID)=" & lookupValue & "))"
CurrentDb.Execute updateQnty, dbFailOnError

vb.net Syntax error in INSERT INTO Statement with access

I'm getting an error during my insert can someone take a look?
Table:
VB.NET
Dim Name As String = txtName.Text
Dim JoinDate As String = dpJoinDate.Value
Dim DOB As String = dpDOB.Value
Dim ParentsName As String = txtParentsName.Text
Dim School As String = txtSchool.Text
Dim STD As String = txtSTD.Text
Dim Address As String = txtAddress.Text
Dim EMail As String = txtEMail.Text
Dim Mobile1 As String = txtMobile1.Text
Dim Mobile2 As String = txtMobile2.Text
Dim DurationStart As Date = dpDurationStart.Value
Dim DurationEND As Date = dpDurationEND.Value
Dim Fees As Decimal = Decimal.Parse(0.0)
Dim MaterialFees As Decimal = Decimal.Parse(0.0)
Dim LateFees As Decimal = Decimal.Parse(0.0)
Dim NextRenewal As Date = dpNextRenewal.Value
Dim Centre As String = cbCentre.Text
Dim Coach As String = cbCoach.Text
Dim picture As String = lblFileName.Text
Try
Fees = Decimal.Parse(txtFees.Text)
Catch
End Try
Try
MaterialFees = Decimal.Parse(txtMaterialFees.Text)
Catch
End Try
Try
LateFees = Decimal.Parse(txtLateFees.Text)
Catch
End Try
Dim Cmd As OleDbCommand
Dim SQL As String
Dim objCmd As New OleDbCommand
Dim Con = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=./AcademyDatabase.accdb;Persist Security Info=False;")
SQL = "INSERT INTO Student (FullName,JoinDate,DOB,ParentsName,School,STD,Address,EMail,Mobile1,Mobile2,DurationStart,DurationEND,Fees,MaterialFees,LateFees,NextRenewal,Centre,Coach,Image,DropOut) VALUES ('" _
& Name & "','" _
& JoinDate & "','" _
& DOB & "','" _
& ParentsName & "','" _
& School & "','" _
& STD & "','" _
& Address & "','" _
& EMail & "','" _
& Mobile1 & "','" _
& Mobile2 & "','" _
& DurationStart & "','" _
& DurationEND & "','" _
& Fees & "','" _
& MaterialFees & "','" _
& LateFees & "','" _
& NextRenewal & "','" _
& Centre & "','" _
& Coach & "','" _
& picture & "'," _
& "0)"
Cmd = New OleDbCommand(SQL, Con)
Con.Open()
objCmd = New OleDbCommand(SQL, Con)
Dim rowCount As Integer = 0
Try
rowCount = objCmd.ExecuteNonQuery()
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
Sql:
"INSERT INTO Student (FullName,JoinDate,DOB,ParentsName,School,STD,Address,EMail,Mobile1,Mobile2,DurationStart,DurationEND,Fees,MaterialFees,LateFees,NextRenewal,Centre,Coach,Image,DropOut) VALUES ('','3/13/2014','1/1/1900','','fadsasdffdas','','','','','','1/1/1900','1/1/1900','0','0','0','1/1/1900','','','',0)"
IMAGE is a reserved keyword. If you want to use it for a column name, then your need to encapsulate it with square brackets
"INSERT INTO Student " & _
"(FullName,JoinDate,DOB,ParentsName,School,STD,Address," & _
"EMail,Mobile1,Mobile2,DurationStart,DurationEND,Fees," & _
"MaterialFees,LateFees,NextRenewal,Centre,Coach,[Image],DropOut) VALUES ...."
If you are still able to do so, I suggest to change the name of that column to a NON reserved keyword, otherwise you will alway have this problem when you try to use that column.
Said that, please, read about parameterized queries. Your code has a big problem and it is called SQL Injection (not to mention the parsing problems for strings, date and decimals)
SQL = "INSERT INTO Student " & _
"(FullName,JoinDate,DOB,ParentsName,School,STD,Address," & _
"EMail,Mobile1,Mobile2,DurationStart,DurationEND,Fees," & _
"MaterialFees,LateFees,NextRenewal,Centre,Coach,[Image],DropOut) " & _
"?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,0)"
Con.Open()
objCmd = New OleDbCommand(SQL, Con)
objCmd.Parameters.AddWithValue("#p1", Name)
objCmd.Parameters.AddWithValue("#p2", JoinDate)
.... add the other missing parameters with their values.....
objCmd.Parameters.AddWithValue("#p18", picture)
Dim rowCount As Integer = 0
rowCount = objCmd.ExecuteNonQuery()

Updating Access Database using UPDATE SQL statement in VBA

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).

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 & "'"