want to update record if exists and insert if not exists - vb.net

want to update record if exists and insert if not exists into vsolv_trn_tsalesregdump Is tsalesregdump_name is unique in table vsolv_trn_tsalesregdump
when i click check box that particular row should be check on other table and how to use it for loop in form loop i can use the "tsalesdump_date,tsalesdump_name,executivename_executive" this three if the value is same its go to update and otherwise its not to same its move on insert how can i write it can any 1help me
if i have use two table one temp and other 1 is orginal\ temp table =vsolv_tmp_tsalesdump orginal table=vsolv_trn_tsalesregdump.
if already i hav save the data in orginal table,again if i hav assing data for temp table and view in radgrid if select and submit the button its go to check on orginal table if the value is already there its update it otherwise insert how can use it
Protected Sub btn_Submit_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btn_Submit.Click
lblerrmsg.Text = ""
Dim chk As CheckBox
Dim lbtn As LinkButton
Dim Res As Long
Dim lobjrow As DataRow
Dim lObjErrTable As New DataTable
Dim a As Integer = 0
Dim dtcarbooking As New DataTable
Dim dtDumpBooking As New DataTable
Dim lsRefid As String = String.Empty
Dim dtdumpsample As New DataTable
Dim name As String = String.Empty
If Check_Validation() = True Then
Exit Sub
End If
Gobjdbconn.OpenConn()
lObjErrTable = Error_TabelFill()
For i As Integer = 0 To GVUpload.Items.Count - 1
chk = GVUpload.Items(i).FindControl("chkupload")
If chk.Checked = True Then
lsRefid = GVUpload.Items(i).GetDataKeyValue("tsalesdump_gid").ToString()
MsSql = ""
MsSql &= "Select tsalesdump_gid,tsalesdump_date,tsalesdump_name,executivename_executive,tsalesdump_vch_no,tsalesdump_debit,tsalesdump_credit"
MsSql &= " from vsolv_tmp_tsalesdump as a"
MsSql &= " left join vsolv_trn_executivename as b on a.tsalesdump_name = b.executivename_particulars"
MsSql &= " where tsalesdump_gid = '" & lsRefid & "' and tsalesdump_isremoved = 'N'"
dtDumpBooking = Gobjdbconn.GetDataTable(MsSql)
MsSql = ""
MsSql &= "Insert into vsolv_trn_tsalesregdump(tsalesregdump_date,tsalesregdump_name,tsalesregdump_executive,tsalesregdump_vch_no"
MsSql &= " ,tsalesregdump_debit,tsalesregdump_credit,tsalesregdump_importby)"
MsSql &= " Values ('" & Format(CDate(dtDumpBooking.Rows(0).Item("tsalesdump_date")), "yyyy-MMM-dd").ToString() & "'"
MsSql &= ",'" & dtDumpBooking.Rows(0).Item("tsalesdump_name").ToString() & "'"
MsSql &= ",'" & dtDumpBooking.Rows(0).Item("executivename_executive").ToString() & "'"
MsSql &= " ,'" & dtDumpBooking.Rows(0).Item("tsalesdump_vch_no").ToString() & "'"
MsSql &= " ,'" & dtDumpBooking.Rows(0).Item("tsalesdump_debit").ToString() & "','" & dtDumpBooking.Rows(0).Item("tsalesdump_credit").ToString() & "','SIVA')"
MnResult = Gobjdbconn.ExecuteNonQuerySQL(MsSql)
If MnResult = 1 Then
MsSql = ""
MsSql &= " Delete from vsolv_tmp_tsalesdump where tsalesdump_gid = '" & lsRefid & "'"
Gobjdbconn.ExecuteNonQuerySQL(MsSql)
Else
lobjrow = lObjErrTable.NewRow()
a = a + 1
lobjrow("Sno") = a
lobjrow("Booking Ref No") = dtcarbooking.Rows(0).Item("tsalesregdump_name").ToString
lobjrow("Description") = "Duplicate Record"
lObjErrTable.Rows.Add(lobjrow)
End If
End If
Next
POPSummary()
If Not lObjErrTable Is Nothing Then
If lObjErrTable.Rows.Count > 0 Then
Call Pop_Data(lObjErrTable)
End If
End If
End Sub

If you want to update record if already exists else insert in SQL then you can achieve by following: You need to change MsSql string for Insert command
MsSql = "" + _
"IF EXISTS(Select tsalesregdump_name From vsolv_trn_tsalesregdump Where tsalesregdump_name = '" & dtDumpBooking.Rows(0).Item("tsalesdump_name").ToString() & "') " + _
"BEGIN " + _
" Update vsolv_trn_tsalesregdump " + _
" Set tsalesregdump_date = '" & Format(CDate(dtDumpBooking.Rows(0).Item("tsalesdump_date")), "yyyy-MMM-dd").ToString() & "' " + _
" ,tsalesregdump_executive = '" & dtDumpBooking.Rows(0).Item("executivename_executive").ToString() & "' " + _
" ,tsalesregdump_vch_no = '" & dtDumpBooking.Rows(0).Item("tsalesdump_vch_no").ToString() & "' " + _
" ,tsalesregdump_debit = '" & dtDumpBooking.Rows(0).Item("tsalesdump_debit").ToString() & "' " + _
" ,tsalesregdump_credit = '" & dtDumpBooking.Rows(0).Item("tsalesdump_credit").ToString() & "' " + _
" ,tsalesregdump_importby = 'SIVA' " + _
" Where tsalesregdump_name = '" & dtDumpBooking.Rows(0).Item("tsalesdump_name").ToString() & "' " + _
"END " + _
"ELSE " + _
"BEGIN " + _
" Insert into vsolv_trn_tsalesregdump(tsalesregdump_date,tsalesregdump_name,tsalesregdump_executive,tsalesregdump_vch_no " + _
" ,tsalesregdump_debit,tsalesregdump_credit,tsalesregdump_importby) " + _
" Values ('" & Format(CDate(dtDumpBooking.Rows(0).Item("tsalesdump_date")), "yyyy-MMM-dd").ToString() & "' " + _
" ,'" & dtDumpBooking.Rows(0).Item("tsalesdump_name").ToString() & "' " + _
" ,'" & dtDumpBooking.Rows(0).Item("executivename_executive").ToString() & "' " + _
" ,'" & dtDumpBooking.Rows(0).Item("tsalesdump_vch_no").ToString() & "' " + _
" ,'" & dtDumpBooking.Rows(0).Item("tsalesdump_debit").ToString() & "','" & dtDumpBooking.Rows(0).Item("tsalesdump_credit").ToString() & "','SIVA') " + _
"END "
MnResult = Gobjdbconn.ExecuteNonQuerySQL(MsSql)
I am assuming here that tsalesregdump_name is unique.

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

Dynamically run strings in a loop

I want to run a string dynamically.
I'm trying to run a VBA loop to build a SQL Union for each record after the first. There could be anywhere from 1 record to 100. I want this to be dynamic so I don't have to limit the number of entries.
Example:
If I have 5 records it creates the SQL query with 4 unions. All the same data etc.
I'm trying to do is this:
When someone opens a form they will enter a list of pack numbers, from that they will select the range of offers under each pack number (All Offers, Promo, or Buyer).
The code then builds a union query for each pack number based on the the offer range they selected.
The output is all the data on those Offers under that pack number.
My full code: (I thought it necessary to get the full picture)
Private Sub ReviewButton_Click()
Dim Owner As String
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim qdfPassThrough As QueryDef
Dim strSeasonSQL As String
Dim strSeason As String
Dim strType As String
Owner = GetNamespace("MAPI").Session.CurrentUser.AddressEntry
If Me.NewRecord = True Then
Me!Owner.Value = Owner
End If
Set db = CurrentDb
Set rs = CurrentDb.OpenRecordset("RetailEntry")
'Set rs = CurrentDb.OpenRecordset("SELECT * FROM RetailEntry")
strSeason = [Forms]![Retail_Navigation]![NavigationSubform].[Form]![cboSeason]
strType = rs.Fields("Offer").Value '[Forms]![ReviewButton]![RetailEntry].[Form]![Offer].Value
On Error GoTo 1
1:
'Build Initial Query based on first record and make sure there are records
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
If Not (rs.EOF And rs.BOF) Then
rs.MoveFirst
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'All Offers
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
If rs.Fields("Offer") = "All Offers" Then
StrSQL = "Set NoCount ON DROP TABLE #catcov; " _
& "SELECT DISTINCT mailyear, offer, description, firstreleasemailed, season_id, offer_type, " _
& "case when description like '%Promo%' then 'Promo' " _
& "Else 'Buyer' end As addtype " _
& "INTO #catcov " _
strSELECT = "FROM supplychain_misc.dbo.catcov; " _
& "SELECT DISTINCT " _
& "a.PackNum " _
& ",a.Description " _
& ",a.CatID " _
& ",DATEPART(QUARTER, FirstReleaseMailed) as Quarter " _
& ",a.RetOne " _
& ",a.Ret2 " _
& ",a.ORIGINALRETAIL " _
& ",a.DiscountReasonCode " _
& ",b.Season_id " _
& ",a.year " _
& ",addtype "
strFROM = "FROM PIC704Current a JOIN #CatCov b ON (a.CatID = b.Offer) and (a.Year = b.MailYear) " _
strWHERE = "WHERE b.Offer_Type In('catalog', 'insert', 'kicker', 'statement insert', 'bangtail', 'onsert', 'outside ad') " _
& " and b.Season_id = '" & strSeason & "' " _
& " and (Case when b.FirstReleaseMailed >= cast(dateadd(day, +21, getdate()) as date) then 1 else 0 end) = 1 "
StrSQL = StrSQL & vbCrLf & strSELECT & vbCrLf & strFROM & vbCrLf & strWHERE
'Promo/Core
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
ElseIf rs.Fields("Offer") = "Promo" Or rs.Fields("Offer") = "Buyer" Then
StrSQL = "Set NoCount ON DROP TABLE #catcov; " _
& "SELECT DISTINCT mailyear, offer, description, firstreleasemailed, season_id, offer_type, " _
& "case when description like '%Promo%' then 'Promo' " _
& "Else 'Buyer' end As addtype " _
& "INTO #catcov " _
strSELECT = "FROM supplychain_misc.dbo.catcov; " _
& "SELECT DISTINCT " _
& "a.PackNum " _
& ",a.Description " _
& ",a.CatID " _
& ",DATEPART(QUARTER, FirstReleaseMailed) as Quarter " _
& ",a.RetOne " _
& ",a.Ret2 " _
& ",a.ORIGINALRETAIL " _
& ",a.DiscountReasonCode " _
& ",b.Season_id " _
& ",a.year " _
& ",addtype "
strFROM = "FROM PIC704Current a JOIN #CatCov b ON (a.CatID = b.Offer) and (a.Year = b.MailYear) " _
strWHERE = "WHERE b.Offer_Type In('catalog', 'insert', 'kicker', 'statement insert', 'bangtail', 'onsert', 'outside ad') " _
& " and b.Season_id = '" & strSeason & "' and b.addtype = '" & strType & "' " _
& " and (Case when b.FirstReleaseMailed >= cast(dateadd(day, +21, getdate()) as date) then 1 else 0 end) = 1 "
StrSQL = StrSQL & vbCrLf & strSELECT & vbCrLf & strFROM & vbCrLf & strWHERE
End If
'Build/Loop Unions for each record after the first
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
rs.MoveNext
strType = rs.Fields("Offer").Value
Do Until rs.EOF = True
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'All Offers
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
If rs.Fields("Offer") = "All Offers" Then
StrUnion = "UNION SELECT DISTINCT " _
& "a.PackNum " _
& ",a.Description " _
& ",a.CatID " _
& ",DATEPART(QUARTER, FirstReleaseMailed) as Quarter " _
& ",a.RetOne " _
& ",a.Ret2 " _
& ",a.ORIGINALRETAIL " _
& ",a.DiscountReasonCode " _
& ",b.Season_id " _
& ",a.year " _
& ",addtype "
strFROMnxt = "FROM PIC704Current a JOIN #CatCov b ON (a.CatID = b.Offer) and (a.Year = b.MailYear) " _
strWHEREnxt = "WHERE b.Offer_Type In('catalog', 'insert', 'kicker', 'statement insert', 'bangtail', 'onsert', 'outside ad') " _
& " and b.Season_id = '" & strSeason & "' " _
& " and (Case when b.FirstReleaseMailed >= cast(dateadd(day, +21, getdate()) as date) then 1 else 0 end) = 1 "
StrSQL2 = StrUnion & vbCrLf & strFROMnxt & vbCrLf & strWHEREnxt
'Promo/Buyer
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
ElseIf rs.Fields("Offer") = "Promo" Or rs.Fields("Offer") = "Buyer" Then
StrUnion = "UNION SELECT DISTINCT " _
& "a.PackNum " _
& ",a.Description " _
& ",a.CatID " _
& ",DATEPART(QUARTER, FirstReleaseMailed) as Quarter " _
& ",a.RetOne " _
& ",a.Ret2 " _
& ",a.ORIGINALRETAIL " _
& ",a.DiscountReasonCode " _
& ",b.Season_id " _
& ",a.year " _
& ",addtype "
strFROMnxt = "FROM PIC704Current a JOIN #CatCov b ON (a.CatID = b.Offer) and (a.Year = b.MailYear) " _
strWHEREnxt = "WHERE b.Offer_Type In('catalog', 'insert', 'kicker', 'statement insert', 'bangtail', 'onsert', 'outside ad') " _
& " and b.Season_id = '" & strSeason & "' and b.addtype = '" & strType & "' " _
& " and (Case when b.FirstReleaseMailed >= cast(dateadd(day, +21, getdate()) as date) then 1 else 0 end) = 1 "
StrSQL2 = StrUnion & vbCrLf & strFROMnxt & vbCrLf & strWHEREnxt
End If
'Move to next Record and loop till EOF
rs.MoveNext
Loop
'If there are no Records then error
Else
MsgBox "There are no Pack Numbers Entered."
End If
'END QUERY
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'Build Retail Bump File Pass Through Query
db.QueryDefs.Delete "qryMaster"
Set qdfPassThrough = db.CreateQueryDef("qryMaster")
qdfPassThrough.Connect = "ODBC;DSN=SupplyChainMisc;Description=SupplyChainMisc;Trusted_Connection=Yes;DATABASE=SupplyChain_Misc;"
qdfPassThrough.ReturnsRecords = True
qdfPassThrough.sql = StrSQL & vbCrLf & StrSQL2
rs.Close
Set rs = Nothing
DoCmd.OpenForm "SubCanButton"
DoCmd.OpenQuery "MasterQuery"
DoCmd.Close acForm, "ReviewButton"
End Sub
First, you do a "union distinct" when you don't include ALL:
UNION ALL
SELECT DISTINCT ...
Thus, as your selected records seem the same, only one will returned.
Second, including ALL or not, your concept doesn't make much sense. Why union a lot of identical records? Even if they hold different IDs only, they seem to be pulled from the same table, which you could with a single query.
Third, casting a date value to a date value does nothing good, so:
cast(dateadd(day, +21, getdate()) as date)
can be reduced to:
dateadd(day, +21, getdate())

MS Access 2010 VBA Integer Variable not changing in Loop

I have code that is looping through an array of member numbers and retrieving records for each. Each time, I need to use the count of the records returned up to 12. However, once the variable that is to hold the count is set, it will not reset with the next call. It also "jumps" from the first to the last record rather than looping through each. In other words, if there are 4 records returned by the recordset, it will execute for the first and the last and then give an error of "No Current Record" Here is my code:
Dim x As Integer
For i = 1 To intMembers
strGetMemberInfo = "SELECT PatientRecords.[Medication Name], PatientRecords.[First Name], PatientRecords.[Last Name],PatientRecords.[doc phone]" _
& " FROM PatientRecords WHERE member_no ='" & arrMembers(i) & "'"
Set rstMedicine = dbs.OpenRecordset(strGetMemberInfo, dbOpenSnapshot)
Dim intMedicine As Integer
intMedicine = rstMedicine.RecordCount
If intMedicine > 12 Then
intMedicine = 12
End If
Do Until rstMedicine.EOF
For x = 1 To intMedicine
strMedicationField = strMedication & x
strDoctorFNameField = strDoctorFName & x
strDoctorLNameField = strDocotrLName & x
strDoctorPhoneField = strDoctorPhone & x
strSQL = "UPDATE TransformationTable SET " & strMedicationField & " = '" & rstMedicine.Fields("[Medication Name]").Value & "'," & strDoctorFNameField & " = '" & rstMedicine.Fields("[First Name]").Value & "', " & strDoctorLNameField & " = '" & Replace(rstMedicine.Fields("[Last Name]"), "'", "''") & "', " & strDoctorPhoneField & " = '" & rstMedicine.Fields("[doc phone]").Value & "' WHERE member_no ='" & arrMembers(i) & "'"
dbs.Execute strSQL
rstMedicine.MoveNext
Next x
Loop
rstMedicine.Close
Set rstMedicine = Nothing
Next i
In the above code, intMedicinegets set by the first recordset and NEVER changes even though rstMedicine.RecordCount does change.
Any help is appreciated
You have 2 different issues. First, use rstMedicine.MoveLast to move to the bottom of the recordset and get the full count. Second. Your limiting the number of "cycles" to 12, but you are not exiting the loop after intMedicine is 12, so it is still trying to get to the end of the recordset because your code says "Do Until rstMedicine.EOF". Change your code to this:
Dim x As Integer
For i = 1 To intMembers
strGetMemberInfo = "SELECT PatientRecords.[Medication Name], PatientRecords.[First Name], PatientRecords.[Last Name],PatientRecords.[doc phone]" _
& " FROM PatientRecords WHERE member_no ='" & arrMembers(i) & "'"
Set rstMedicine = dbs.OpenRecordset(strGetMemberInfo, dbOpenSnapshot)
rstMedicine.MoveLast
Dim intMedicine As Integer
intMedicine = rstMedicine.RecordCount
If intMedicine > 12 Then
intMedicine = 12
End If
rstMedicine.MoveFirst
Do Until rstMedicine.EOF
For x = 1 To intMedicine
strMedicationField = strMedication & x
strDoctorFNameField = strDoctorFName & x
strDoctorLNameField = strDocotrLName & x
strDoctorPhoneField = strDoctorPhone & x
strSQL = "UPDATE TransformationTable SET " & strMedicationField & " = '" & rstMedicine.Fields("[Medication Name]").Value & "'," & strDoctorFNameField & " = '" & rstMedicine.Fields("[First Name]").Value & "', " & strDoctorLNameField & " = '" & Replace(rstMedicine.Fields("[Last Name]"), "'", "''") & "', " & strDoctorPhoneField & " = '" & rstMedicine.Fields("[doc phone]").Value & "' WHERE member_no ='" & arrMembers(i) & "'"
dbs.Execute strSQL
rstMedicine.MoveNext
If x = 12 Then
Exit Do
End If
Next x
Loop
rstMedicine.Close
Set rstMedicine = Nothing
Next i

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

Passing an Empty/Null Date variable in VBA to an SQL UPDATE statement

I have an excel userform with various textboxes, some are fields to enter dates. The user can then save their entries.
At this point, I connect to an access backend via an ADO connection. The values entered by a user are passes to an SQL string, e.g.
strSQL = "UPDATE tblDECONVERSION_DATA SET tblDECONVERSION_DATA.Status = '" & NewBusiness_WorkQueue.Decon_CaseStatus & "', " & _
"tblDECONVERSION_DATA.DMS = '" & NewBusiness_WorkQueue.Decon_DMS & "', " & _
"tblDECONVERSION_DATA.DateRecieved = #" & Format(NewBusiness_WorkQueue.Decon_DateRecieved, "mm/dd/yyyy") & "#, " & _
"tblDECONVERSION_DATA.WireDate = #" & Format(NewBusiness_WorkQueue.Decon_WireDate, "mm/dd/yyyy") & "#, " & _
"tblDECONVERSION_DATA.LastEditXID = '" & CurrUser & "', tblDECONVERSION_DATA.LastEditDate = #" & Now & "# " & _
"WHERE (((tblDECONVERSION_DATA.CaseID)=" & ID & "));"
adoRecSet.Open Source:=strSQL, ActiveConnection:=dbconnect, CursorType:=adOpenDynamic, LockType:=adLockOptimistic
However, some of the date fields can be left blank, meaning for example the NewBusiness_WorkQueue.Decon_DateRecieved variable being empty. This causes a syntax error. How can I pass a Null or Empty date variable in the SQL statement that both VBA and the access database will accept?
strSQL = "UPDATE tblDECONVERSION_DATA SET tblDECONVERSION_DATA.Status = '" & _
NewBusiness_WorkQueue.Decon_CaseStatus & "', " & _
"tblDECONVERSION_DATA.DMS = '" & NewBusiness_WorkQueue.Decon_DMS & "', " & _
"tblDECONVERSION_DATA.DateRecieved = " & _
DateOrNull(NewBusiness_WorkQueue.Decon_DateRecieved) & ", " & _
"tblDECONVERSION_DATA.WireDate = " & _
DateOrNull(NewBusiness_WorkQueue.Decon_WireDate) & ", " & _
"tblDECONVERSION_DATA.LastEditXID = '" & CurrUser & _
"', tblDECONVERSION_DATA.LastEditDate = #" & Now & "# " & _
"WHERE tblDECONVERSION_DATA.CaseID=" & ID & ";"
An example function:
Function DateOrNull(v) As String
Dim rv as String
If IsDate(v) Then
rv = " #" & Format(v, "mm/dd/yyyy") & "# "
Else
rv = " null "
End If
DateOrNull = rv
End Function