SQL Select statement suddenly retrieving wrong value only when selecting form another query - sql

I have a order creation form in an Access database where the user selects a product and VBA code is triggered with SQL select statement to retrieve the current availability of that product. This is how it's set up:
I have a Packages table where products batches are added to inventory.
I have an OrderDetail table where items from product batches are allocated to orders.
I have a InventoryPrep query with a the total packaged per batch and field that sums the number of allocated products per batch from the OrderDetail table.
Then I have an Inventory query that that has a calculated field that takes the TotalPackaged field from the InventoryPrep query and subtracts the TotalAllocated field from the InventoryPrep query.
Here is the VBA code in my form, triggered by an update to the [Batch] combo box:
Dim VBatch As String
VBatch = Me.Batch.Value
Dim VAvail As Double
Dim mySQL As String
Dim conn1 As ADODB.Connection
Set conn1 = CurrentProject.Connection
Dim rs1 As New ADODB.Recordset
rs1.ActiveConnection = conn1
mySQL = "SELECT Available FROM Inventory WHERE BatchID = " & "'" & VBatch & "'"
rs1.Open mySQL
rs1.MoveFirst
VAvail = rs1.Fields("Available").Value
Forms!ChangeOrders.ChangeOrderSubform.Form.Availability.Value = VAvail
rs1.Close
conn1.Close
Set rs1 = Nothing
Set conn1 = Nothing
This has been working just fine for weeks, retreiving the correct available amount as packaged items are added to the Packages table and orders are being added in the OrderDetail table. Yesterday it started returning the Packaged field from the InventoryPrep query instead.
I tried a bunch of things and then created a table from the query and used the SELECT statement to look it up in the table. That worked. There is something about my query set up that has caused it to stop recognizing my calculated field. I need help!
This is my first time posting and I hope this is enough information. I'm pretty new to Access and VBA but I've learned a lot from reading in this forum. I hope someone can help or let me know what other information could shed light on the problem.

To read a single value from a table or query, your code is a bit over the top.
For this scenario, Access has the DLookup function.
VAvail = DLookup("Available", "Inventory", "BatchID = '" & VBatch & "'")
Forms!ChangeOrders.ChangeOrderSubform.Form.Availability.Value = VAvail
That's all that is needed.

Related

How do I update a single field of a single record with data from another table with VBA in MS Access

In MS Access, I have a table called "Products". It contains quality testing parameters, as well as fields for "Part_No" and "Last_Test_Date". The "Last_Test_Date" field being the last time that the specific product was tested.
I have another table (Trend001) that is live updated with the actual test data from a hydraulic test machine, as well as the "Part_No" being tested and a current "Time_Stamp".
I would like to update the "Last_Test_Date" of the specific "Part_No" being tested with the "Time_Stamp" from the "Trend001" table.
That way the user knows the last time that the Part was tested.
I found this on Stackoverflow, but I don't know enough about the language to apply it to my project.
Updating existing records and adding new records in table (MS Access VBA)
'''
Public Sub UpdateExistingRecords()
On Error GoTo ErrTrap
Dim rs As DAO.Recordset
Set rs = CurrentDb().OpenRecordset("SELECT * FROM tblTempData", dbOpenSnapshot)
Set rsCommon = CurrentDb().OpenRecordset("SELECT * FROM tblCommon", dbOpenDynaset)
Dim idx As Long
For idx = 1 To rs.RecordCount
If ExistsInCommon(rs![Item ID]) Then
If Not Update(rs) Then
MsgBox "Failed to update.", vbExclamation
GoTo Leave
End If
'''
You don't need VBA to do the update, just use a SQL update. This SQL will update all the parts in the Products table that exist in the Trend001 table.
UPDATE Products INNER JOIN Trend001 ON Products.Part_No = Trend001.Part_No
SET Products.Last_Test_Date = Trend001.Time_Stamp;
PLEASE - Remember to back up your database before running this update. A small typo could delete your data.

Why is the value extracted from database not showing what is intended?

I have the following SQL Statement:
SELECT StockChild.ProductId, Sum(StockChild.Qty) AS SumOfQty,
PRODUCTDETAILS.Title, Sum(SALESORDERchild.Stockout) AS SumOfStockout
FROM (PRODUCTDETAILS
INNER JOIN SALESORDERchild
ON PRODUCTDETAILS.productID = SALESORDERchild.ProductId)
INNER JOIN StockChild
ON PRODUCTDETAILS.productID = StockChild.ProductID
WHERE (((StockChild.ProductID)=[Forms]![StockChild]![ProductId])
AND ((SALESORDERchild.ProductID)=[Forms]![StockChild]![ProductId]))
GROUP BY StockChild.ProductId, PRODUCTDETAILS.Title;
I'm trying to get the summation of values from 2 different tables using the above SQL Statement in access:
1) Sum of StockChild quantity based on productID
2) Sum of Salesorderchild Stockout based on productID
If i query it separately, i managed to get the values that i needed but i'm unable to put it into a single form.
but when i query it together as above, the values jump all over the place and i can't seem to understand why.
And if i add another record in the salesorderchild, of the already existing isbn, all the values will jump as well.
is there something that i am doing wrongly? or how should i go about to tackle this matter.
I added some explanations in the image attached.
Update:
I was trying another method whereby i just did a normal query for the initial stock to be displayed(which worked fine getting the numbers i need)
and over in the Total stockout i was trying out a
=DSum("[stockout]","[SALESORDERchild]","[ProductId]=" & [Forms]!
[StockChild]![ProductId])
but it was returning me a #Name? did i use this correctly?, should i do a vba code instead or is there a way to do it this way?
i tried the following vba code function as an alternative to select out the value but it was telling me the user-defined type not defined. am i missing out something? - (fixed this part by defining the reference of active x data object)
Private Sub Form_Current()
Dim intI As Integer
Dim fld As Field
Dim rst As ADODB.Recordset
Dim pid As String
pid = ProductID.Value
Set rst = New ADODB.Recordset
rst.Open "SELECT Sum(SALESORDERchild.Stockout) AS SumOfStockout FROM
SALESORDERchild WHERE SALESORDERchild.ProductID ='" & pid & "';",
CurrentProject.Connection, adOpenKeyset, adLockOptimistic
tb_stockout.Value = rst.Fields("SumOfStockout")
End Sub
Done Thanks everyone :)

MS Access VBA query. Select followed by a count of the result

I have asked a similar question recently. However, I don't think I knew the extent of what I was wanting to accomplish with my VBA at that time. I am using Access 2010 and creating an on_click command within a form.
So my intention is to create a query, and the approach I was going to take was as follows:
varSQL2 = "SELECT * FROM Inventory WHERE Part_ID=" & rs!Part_ID & ";"
Set rs2 = db.OpenRecordset(varSQL2, dbOpenDynaset)
varStock_Level = rs2!Stock_Level +rs!Quantity
the rs!quantity and rs!Part_ID are from another query earlier in my code. stock_level and part_ID are fields in the Inventory table.
I now need to be able to create a query to count how many records came back as a result of varSQL2. so I can do something along the lines of:
varSQL2 = "SELECT * FROM Inventory WHERE Part_ID=" & rs!Part_ID & ";"
Set rs2 = db.OpenRecordset(varSQL2, dbOpenDynaset)
varStock_Level = rs2!Stock_Level +rs!Quantity
if count >1 then
....[code]....
end if
I don't really know where to start with this, slightly confused my self with subqueries. I believe I need 2 queries not one. Any help is appreciated.
There are several ways:
Create a query with COUNT function (similar as you did in refered question)
Use your query, use the rs2.movelast and read count out with rs2.RecordCount
Use domain count
Dim lngRows As Long
lngRows = DCount("*", "Inventory", "Part_ID='" & rs!Part_ID & "'")
From memory:
rs.movelast
debug.print rs.recordCount
You must always Movelast before using RecordCount. I your table/query is big, it can be time consuming.

Access SQL How to select randomly a group of contiguous rows

can this be done, say I have rows (1,2,3,4,5) and I want to grab three rows, select one randomly and then get it's neighbors, so maybe the random selection is row (3), I can also grab (2,4) if I wanted its neighbors, do I just pick one at random and then look for the unique key before and after like this or can I do it all in one sql statement.
I was going to use ADO from excel to pull records (so VBA connects to access, opens a recordset with sql instructions and so on).
Hope I was clear!
I would love to just do this all in a SQL statement
I am not sure Access is capable of all the SQL commands such as SQL Server, so this may be a bit of a problem. If you have a primary key though, you can easly generate a Select query in VBA and then pass open recordset with this SQL.
Dim sSQL as String
Dim lRand as Long
Dim rs as ADODB.Recordset 'or DAO.Recordset'
lRand = VBA.Int(VBA.Rnd() * TableRecordCount) ' TableRecordCount is the number of records in the table that you need to get somehow'
sSQL = "SELECT * FROM TableName WHERE (ID>=" & lRand - 1 & " AND ID <=" & lRand + 1
set rs = CurrentDB.OpenRecordset(sSQL, ...)
I am now not absolutely sure of what you want to use and depending on ADODB or DAO choice, you need to open the recordset accordingly with wither Call rs.Open or Set rs = DB.OpenRecordset

Update table while reading

I'm writing a piece of code (VB.NET) to cleanse a (quite big) table of data.
I am connecting to my SQL database, looping through the table, cleansing the data and adding the cleansed data in a different column.
As i'm currently doing an update to my database for each record in the same loop as where i am cleansing the data, i am wondering if there is a more efficient way of doing this, where i would cleanse the data and afterwards send all the updated records to the database in one go.
Simplified code:
'Connect
SQLConn.ConnectionString = strConnection
SQLConn.Open()
SQLCmd.Connection = SQLConn
SQLConn2.ConnectionString = strConnection
SQLConn2.Open()
SQLCmd2.Connection = SQLConn2
'Set query
strSQL = "SELECT Column1 FROM Table1"
SQLCmd.CommandText = strSQL
'Load Query
SQLdr = SQLCmd.ExecuteReader
'Start Cleansing
While SQLdr.Read
Cleansing()
'Add to database
strSQL2 = "UPDATE Table1 SET Clean_data = '" & strClean & "' WHERE Dirty_Data = '" & SQLdr(0).ToString & "'"
SQLCmd2.CommandText = strSQL2
SQLCmd2.ExecuteNonQuery()
End While
'Close Connections
SQLdr.Close()
SQLConn.Close()
SQLConn2.Close()
I'm guessing (from searching for a solution) that it is possible to do the update outside of my loop, but i can't seem to find how to do it specifically.
Many thanks!
Your code is taking a long time because the update is doing a full table scan for every record. You can speed it up by adding an index on the column "Dirty Data".
Essentially, you are reading the data in the select statement. Cleaning one row, and then updating it. The preferred "set-based" approach is more like:
Ideally, you would like to do:
update table1
set column1 = <fix the dirty data>
where column1 <is dirty>
And you have some options in SQL, in terms of replace() and case and like (for instance) that can help with this process.
But you already have the cleaning code external to the database. For this, you want to create and open a cursor, process the record, and then write back. Cursors are relatively slow, compared to in-database operations. But, this is exactly the situation they were designed for -- external code to be applied to individual records.