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
Related
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 :)
How should I write the name of the recordset correctly? I have a type mismatch error on & rsg & at "sq3=..." line. Thanks in advance.
Dim rsG As DAO.Recordset
Dim sq2, sq3 As String
sq2 = "SELECT * from GeneralTable "
sq2 = sq2 & "where gsede='LION' and (gExclu is null) and (gAda is null) "
sq2 = sq2 & "order by gnomb,gnif;"
Set rsG = CurrentDb.OpenRecordset(sq2)
sq3 = "UPDATE " & rsG & " SET gsede ='AA' WHERE gsede='LION'"
DoCmd.RunSQL (sq3)
You are mixing up totally different ways to update data - UPDATE SQL and VBA recordset.
If you want to update a recordset row by row, you do something like
Do While Not rsG.EOF
If rsG!foo = "bar" Then
rsG.Edit
rsG!gsede = "AA"
rsG.Update
End If
rsG.MoveNext
Loop
Do the update using a single query:
update generaltable
set gsede = 'AA'
where gsede ='LION' and (gExclu is null) and (gAda is null);
If you do the update off of rsG, then you'll likely do a separate update for each row, and that is inefficient.
You can't mix and match SQL and recordset objects. You can either build a full update statement that includes the logic of the first select (as other answer suggests), or you can open a dynamic recordset and loop through the records programmatically to make the updates.
That being said, looping through large recordsets programmatically to make updates is usually better handled by a bulk SQL statement, unless it is essential to consider each row individually inside the code - which in your basic example would not be the case.
MS has a good article on the DAO.Recordset object. There is a dynamic-type Recordset example about halfway down.
Okay, so I have nearly 200 tables in an Access database. The tables are of plant species abundance data, and I would like to combine them into a master data file. Each table contains basically the same columns of species; however, many are spelled slightly differently.
When I run an SQL query in MS Access it won't let me append the tables with each other because of the field names being spelled just a little different.
Any thoughts that would help?
The query I am running is an append query:
INSERT INTO masterTable SELECT * FROM siteTable
and, as an example, the differences in field names are pretty minor
(e.g. "Spp.A" vs "SppA" or "SpeciesOne" vs "Species1")
Thanks for any help,
Paul
You'll need to use vba for this, you'll also need to change the column names I'm using in the masterTable, which in my example are just column1, column2 & column3, and to set the maximum column index in a couple of places (I've stuck some comments in, so you can see what needs to be changed).
If you dont usually use vba, Create a form with a button, and a click event for the button & put this code in it, then open the form and click the button.
Dim db As Database
Dim tdf As TableDef
Dim ii As Long
dim sql as String
Set db = CurrentDb()
docmd.setwarnings false
For Each tdf In db.TableDefs
'change column list as required:
sql = "INSERT INTO masterTable (Column1, Column2, Column3) SELECT "
'change 2 to maximum column number - 1:
for ii = 0 to 2
sql = sql & tdf.Fields(ii).Name
'change 2 to maximum column number - 1 again:
if ii < 2 then
sql = sql & ","
end if
next
sql = sql & ")"
docmd.runsql sql
Next
docmd.setwarnings true
This should work I think. (I'm hoping there's no syntax errors, as I havent tested it, but the logic isnt exactly rocket science)
Hope this helps
I need to query an XLS "database" from within an Excel Workbook via ADO.
I am using the following:
...code
objRecordset.Open "SELECT * FROM [MY_TABLE$] WHERE Code_ID = " & the_ID & ", objConnection, adOpenStatic, adLockOptimistic, adCmdText
...code
It runs well if I am only searching for an Id (the_ID), eg 1234
But what I need is to search for various the_ID's at the same time....
So for example any matches of ID's 1234, 1225, 6225, 5656 should return on the query.
So more or less an array of Id's.
Any help is appreciated...
You can join the array of ids using Join then use IN in the sql, e.g.
Dim ids(3) As String
ids(0) = "1234"
ids(1) = "1225"
ids(2) = "6225"
Dim sql As String
sql = "SELECT * FROM [MY_TABLE$] WHERE Code_ID IN (" & Join(ids, ",") & ")"
If you are getting your ids from a range then this answer will be of interest to you.
Note
Since you are only querying your own spreadsheet I have assumed security may not be a major concern, however I would normally recommend using parameterised queries, this would either require a known number of ids, or you would have to generate the sql on the fly, something like:
WHERE Code_id IN (#Param1, #Param2, #Param3, #Param4)
It should not be too hard to make your sql like this then add your ids as parameters to the recordset. I haven't used VBA in a long time though, so I can't quite recall the right way to add the parameters (or if it is even possible). If I remember I will update the answer.
I have a table that contains data that I am trying to import into a spreadsheet control on a userform in vba/excel.
The results will be viewed by an end user, so I have set the value of the header cells on initialization as opposed the the column headings from the sql table.
My query looks something like this
Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim sConnString As String
sConnString = "Provider=SQLOLEDB;Data Source=mysource;Initial Catalog=mydatabase;User Id=myusername;Password=mypassword;QuotedID=No"
Set conn = New ADODB.Connection
Set rs = New ADODB.Recordset
conn.Open sConnString
Set rs = conn.Execute("SELECT * FROM WOFT_tbl_clients WHERE userid = '" & UserId.Value & "';")
If Not rs.EOF Then
/////////////////
/something here!/
/////////////////
Else
MsgBox "Error: No records returned.", vbCritical
End If
If CBool(conn.State And adStateOpen) Then conn.Close
Set conn = Nothing
Set rs = Nothing
What I am trying to do is get the output of selected columns from the database and be able to feed them into whatever colomn I like on the spreadsheet control.
So in effect I would somehow like a loop that allows me to output the resultset of columns id, name and userid into the spreadsheet control starting from row 2. My database also contains many other columns which are not needed in this spreadsheet, but will be needed for another spreadsheet control on the same userform, some of which will appear on both.
What I would like to be able to do is have each column in its own recordset, so I could have something like ids stored in a id recordset which I could then use in column A in spreadsheet control 1, and colomn 6 in spreadsheet control 2?
I hope this makes sense! I am using Excel 2010
To have each data column from one table in an extra recordset would lead you to isolated data lists, which wouldn't follow any logic of a relational database model. If the data indeed is isolated in the way, that id is a list, name is another list and so on, living in the same table, then - forgive me - your database model is quite bad.
If you nevertheless want to get only certain columns from your SQL database, specify them in the SQL statement:
SELECT id, name, userid FROM tablename WHERE anycondition ORDER BY name
To loop through every record the recordset object returns, use a do-until loop like this. Don't forget the MoveNext, or it may result in an endless loop.
Do Until rs.EOF
... do anything you want with the record ...
rs.MoveNext
Loop
I hope this is what you needed. Feel free to further explain, if I didn't understand your needs correctly.