Opening a recordset (rs.openrecordset) - ms-access

Guys is there any harm in not using rs.openRecordset after a query string in VBA?
I have the following code and I want to know if this will cause any problems.
Since I'm using strSQL3 in strSQL4, do I need to open strSQL3 using e.g. rs.openrecordset?
strSQL3 = "SELECT DISTINCT SUBQUERY1.FullName, SUBQUERY1.FirstNames, SUBQUERY1.Surname, SUBQUERY1.Company, SUBQUERY1.EmailAddress,& _
& " SUBQUERY1.In_Email, iif(IsNull([SUBQUERY1].[In_Email]) AND IsNull([SUBQUERY2].[Company]),Null,'Email/Company') AS In_Company" _
& " FROM (" & strSQL1 & ") AS SUBQUERY1 LEFT JOIN (" & strSQL2 & ") AS SUBQUERY2 ON SUBQUERY1.Company = SUBQUERY2.Company"
strSQL4 = "SELECT SUBQUERY3.In_Company" _
& " FROM (" & strSQL3 & ") AS SUBQUERY3 WHERE (((SUBQUERY3.In_Company)='Email/Company'))"
Set rs4 = dbs.OpenRecordset(strSQL4)
rs4.MoveLast
rs4.MoveFirst
RsCount = rs4.RecordCount

No problem. Openrecordset query data from database as you asked him by SQL string. If you don`t need to access results of strSQL3 in sub you have no need to open rercordset.

Related

Acces VBA DLOOKUP

Teller = Nz(DLookup("[Teller]", "[Lookuptable]", ("Artikel = '" & ValueArtikel & "' " And " Lookuptable= 'G'")), 0)
Noemer = Nz(DLookup("[Noemer]", "[lookuptable]", ("Artikel = ' " & ValueArtikel & " ' " And Lookuptable= " 'G' ")), 0)
I want to perform a DLOOKUP in acces vba but i can't find the right statement. I looked at many sites and this are the two dlookups that i think are correct but both give the error types don't match. Teller and noemer are integers, Artikel and artikelvalue and Lookuptable are strings. Sorry if this is already asked but i can't find it. i find many posts about it but i can't fixed it. And especcialy sorry for my bad english
The first one is close. Use variables and Debug.Print to help building the strings.
Ctrl+g shows the output.
strCrit = "Artikel = '" & ValueArtikel & "' And Lookuptable= 'G'"
Debug.Print strCrit
Teller = Nz(DLookup("[Teller]", "[Lookuptable]", strCrit), 0)
I use my own function for Lookups because Lookups have a really bad performance.
' Lookups Replacements
'---------------------
Function DLook(Expression As String, Domain As String, Optional Criteria) As Variant
On Error GoTo Err_Handler
Dim strSQL As String
'DCount: strSQL = "SELECT COUNT(" & Expression & ") FROM " & Domain
'Other replacements
'DLookup:
strSQL = "SELECT " & Expression & " FROM " & Domain
'DMax: strSQL = "SELECT MAX(" & Expression & ") FROM " & Domain
'DMin: strSQL = "SELECT SUM(" & Expression & ") FROM " & Domain
'DFirst: strSQL = "SELECT FIRST(" & Expression & ") FROM " & Domain
'DLast: strSQL = "SELECT LAST(" & Expression & ") FROM " & Domain
'DSum: strSQL = "SELECT SUM(" & Expression & ") FROM " & Domain
'DAvg: strSQL = "SELECT AVG(" & Expression & ") FROM " & Domain
If Not IsMissing(Criteria) Then strSQL = strSQL & " WHERE " & Criteria
DLook = DBEngine(0)(0).OpenRecordset(strSQL, dbOpenForwardOnly)(0)
Exit Function
Err_Handler:
MsgBox "Error. Lookup couldnt be performed" & vbNewLine & Err.Description, vbCritical
End Function
Called with:
If DLook("Column2", "Table1", "Column1 = " & ID) = 0 Then
'Do stuff
End If
If DLook("Column2", "Table1") = 0 Then
'Do other stuff
End If

INSERT INTO table with Foreign Key from Form

I am trying to create a Form that is used to manually enter data in certain scenarios. Most data is input from CSV files which is working fine. I have 4 tables, Part , Assembly , MachineOrder , and Job. I was able to write code for entering into the base table, Part, from the Form no problem. The issue now is entering data into the Assembly and MachineOrder tables where the Parts are being referenced by their PID autonumber field and the Assemblies are being referenced by their AID autonumbered field. I have tried many different kinds of methods to perform this of which you can see a bit of in my commented out code. What is there is what I believe to be my closest to correct code thus far with the error now being that Access asks me for the parameter value of rPID even though it is finding the value in the Dlookup function fine. I'm assuming the same is true for the rAID section as well.
Otherwise I'm getting errors of Key Violations when using the INSERT then UPDATE method you see commented out.
The form is called HOTEntry
Any advice on what my problem may be is greatly appreciated, I'm a student and this is my first time trying to use what I've learned in a professional application so any and all constructive criticism is wanted! Apologies if this is a rather specific question but I could really use the help on this since I've been working on it for two days to no avail...
My code:
Sub HOTParts2()
Dim rPID As Integer
Dim rAID As Integer
Dim dbs As DAO.Database
Dim sqlstr1 As String
Dim sqlstr2 As String
Dim sqlstr3 As String
Dim sqlstr4 As String
Set dbs = CurrentDb
'sqlstr1 = "INSERT INTO Assembly ( PID, ModelNum, ModelRev, ModelDescription ) " _
' & "SELECT (PID,Forms!HOTEntry!txtHotModel, Forms!HOTEntry!txtHotRev, Forms!HOTEntry!txtHotDes)" _
' & "FROM Part " _
' & "WHERE Part.PartName = Forms!HOTEntry!txtPartName AND Part.Config = Forms!HOTEntry!txtConfigEntry AND Part.Rev = Forms!HOTEntry!txtRevEntry"
sqlstr1 = "INSERT INTO Assembly ( ModelNum, ModelRev, ModelDescription,PID ) " _
& "VALUES (Forms!HOTEntry!txtHotModel, Forms!HOTEntry!txtHotRev, Forms!HOTEntry!txtHotDes," & "rPID" & ");"
'
'sqlstr2 = "UPDATE Assembly " _
' & "SET PID =" & rPID & " " _
' & "WHERE Assembly.ModelNum = Forms!HOTEntry!txtHotModel And Assembly.ModelDescription = Forms!HOTEntry!txtHotDes And Assembly.ModelRev = Forms!HOTEntry!txtHotRev;"
'
'sqlstr3 = "INSERT INTO MachineOrder ( AID, Serial, CustName ) " _
' & "SELECT (AID,Forms!HOTEntry!txtHotSerial, Forms!HOTEntry!txtHotCust)" _
' & "FROM Assembly" _
' & "WHERE Assembly.Model=Forms!HOTEntry!txtHotModel And ModelDescription= Forms!HOTEntry!txtHotDes And ModelRev = Forms!HOTEntry!txtHotRev; "
sqlstr3 = "INSERT INTO MachineOrder (Serial, CustName, AID ) " _
& "VALUES (Forms!HOTEntry!txtHotSerial, Forms!HOTEntry!txtHotCust," & "rAID" & ");"
'
'sqlstr4 = "UPDATE MachineOrder " _
' & "SET AID =" & rAID & " " _
' & "WHERE AID IS NULL;"
rPID = DLookup("PID", "Part", "PartName = " & "'" & Forms!HOTEntry!txtPartName & "'" & " And " & "Config = " & "'" & Forms!HOTEntry!txtConfigEntry & "'" & " And " & "Rev = " & "'" & Forms!HOTEntry!txtRevEntry & "'")
DoCmd.RunSQL sqlstr1
'DoCmd.RunSQL sqlstr2
rAID = DLookup("AID", "Assembly", "ModelNum = " & "'" & Forms!HOTEntry!txtHotModel & "'" & " And " & "ModelDescription = " & "'" & Forms!HOTEntry!txtHotDes & "'" & " And " & "ModelRev = " & "'" & Forms!HOTEntry!txtHotRev & "'")
DoCmd.RunSQL sqlstr3
'DoCmd.RunSQL sqlstr4
End Sub
Well, if you want to use the looked up rPID and rAID in a query, you need to do more than just set them in VBA. You can either manually fill them in in your SQL statement, use a parameter and a QueryDef and fill in the parameter in your QueryDef, or put the DLookUp inside your SQL statement.
Going with the first approach here, only unquoted rPID in your initial statement, and put it after rPID was set.:
rPID = DLookup("PID", "Part", "PartName = " & "'" & Forms!HOTEntry!txtPartName & "'" & " And " & "Config = " & "'" & Forms!HOTEntry!txtConfigEntry & "'" & " And " & "Rev = " & "'" & Forms!HOTEntry!txtRevEntry & "'")
sqlstr1 = "INSERT INTO Assembly ( ModelNum, ModelRev, ModelDescription,PID ) " _
& "VALUES (Forms!HOTEntry!txtHotModel, Forms!HOTEntry!txtHotRev, Forms!HOTEntry!txtHotDes," & rPID & ");"
DoCmd.RunSQL sqlstr1

Why doesn't this DAO recordset query return any results?

I am working on an Access 2007 database and I have set up a DAO recordset query, however, it is not returning any results. It does not throw up any errors, just no results. Me.ProID is a text field, it includes letters and numbers. I think it has something to do with the text field, maybe the placement of quotations.
Dim contractSQL As String
Dim contractDB As DAO.Database
Dim contractRS As DAO.Recordset
contractSQL = "SELECT Top 1 ContractName, ItemDescription, Price FROM ContractPricing WHERE AccountNo = " & Me.Parent.[AccntNumber] & " AND PartNo = " & """ & Me.ProdID & """ & " ORDER BY Price Asc"
Set contractDB = CurrentDb
Set contractRS = contractDB.OpenRecordset(contractSQL)
Debug.Print contractRS.RecordCount
That string concatenation is likely wrong. " & """ & Me.ProdID & """ & " should almost certainly be '" & Me.ProdID & "'
I don't know if you're referring to this:
contractSQL = "SELECT Top 1 ContractName, ItemDescription, Price FROM ContractPricing WHERE AccountNo = " & Me.Parent.[AccntNumber] & " AND PartNo = " & Me.ProdID & " ORDER BY Price Asc"
I'm not sure if this would help you. I'm also new to this. But hopefully it will.

query a query in VBA

Hi guys I dont know if this makes sense but how can I query another query in VBA?
I will show with example below
This is my first query
strSQL1 = "SELECT DISTINCT SourceBank" _
& ", Fullname, FirstNames" _
& ", Surname, Company" _
& ", EmailAddress" _
& " FROM question" _
& " WHERE FirstNames = '" & strFirstNames & "'" _
Set rs = dbs.OpenRecordset(strSQL)
Then I want to do something like this. Query the first query
strSQL2 = "S"SELECT * from " & strSQL1
Set rs1 = dbs.OpenRecordset(strSQL)
I just want to know if this is possible and if not then what is the best way around it?
All I want to do is to be able to query another query/string/recordset.
thanks
You can do it almost like you've wrote:
strSQL2="SELECT * FROM (" & strSQL1 & ")"
but be sure not to include ; in strSQL1
upd, try:
strSQL2 = "SELECT Question.EmailAddress, SUBQUERY.EmailAddress &" _
& "FROM Question LEFT JOIN (" & strSQL1 & ") AS SUBQUERY ON Question.EmailAddress = SUBQUERY.EmailAddress"
OR just save sql1 into QueryDef (Query in ms access) and use it like source table.

Fastest way of looping in recordset

I have a VB6 application. I have 2 recordsets having the same number of records (almost 50k). Now I have to loop 50k*50k *(number of fields). Can any one tell me the fastest way to do so?
Thanks in advance.
As others have pointed out it is not a good idea to do this client side but here are a few pointers for speeding up recordset access.
Open the recordset as forward only (adOpenForwardOnly) and if you are not writing then read only also.
Refer to the fields by number so instead of doing rs.Fields(“MyField”) you would use rs.Fields(0)
If you are writing back to the database then consider wrapping things up in a transaction to speed things up.
When looping use “Do until rs.EOF” instead of counting records.
Thats all I can think of for now but they should help a bit
There really is no fastest way to do this in vb6.
You'd use 2 for loops.
You might want to give us more details as to why you are pulling down 50k records (twice) and comparing each field. This is usually an indication that something needs to be done on the database side but was brought in to the client side to be solved.
If your two databases are the same and the only difference is the data, you could do something like this (pseudo-code):
SELECT t1.A, t2.A, t2.B, t2.B, ...
FROM t1
INNER JOIN t2 on t1.id = t2.id
WHERE (t1.A <> t2.A) OR (t1.B <> t2.B) OR ...
t1 and t2 would be your two tables. This isn't the most efficient but it would allow you to do the comparisons very easily. Also, you could get more complicated with what you show in the SELECT statement. Currently it is just a listing of both columns side by side.
Having clarified that you've got two Access databases you need to compare, the easiest is to link the two together and then compare with a query.
Right-click the white empty space, Link tables.
Locate you second DB, select the table in it.
Now you can write a query to compare the two. The data being compared is always up to date as it's being pulled through the link.
I have written code to compare and synchronize two data tables many, many times, and I've posted about it here on SO. The key is to use SQL to limit the results to the records that don't match, but the chief insight is to write your on-the-fly SQL ONE COLUMN AT A TIME. With a WHERE clause on each of your SQL statements, this will be much more efficient than any other comparison method.
Within Access, I've written this code to update one table from another. It assumes the tables have the same fields and that there's a PK field that actually identifies the same record in both tables. The code has a dependency on my SQLRun() function to actually execute the SQL, but that line could be replaced with CurrentDB.Execute if you don't want that.
Public Function UpdateTableData(ByVal strSourceTable As String, _
ByVal strTargetTable As String, ByVal strJoinField As String, _
ByRef db As DAO.Database, Optional ByVal strExcludeFieldsList As String, _
Optional ByVal strUpdatedBy As String = "Auto Update", _
Optional strAdditionalCriteria As String) As Boolean
Dim strUpdate As String
Dim rsFields As DAO.Recordset
Dim fld As DAO.Field
Dim strFieldName As String
Dim strNZValue As String
Dim strSet As String
Dim strWhere As String
strUpdate = "UPDATE " & strTargetTable & " INNER JOIN " & strSourceTable _
& " ON " & strTargetTable & "." & strJoinField & " = " _
& strSourceTable & "." & strJoinField
' if the fields don't have the same names in both tables,
' create a query that aliases the fields to have the names of the
' target table
' if the source table is in a different database and you don't
' want to create a linked table, create a query and specify
' the external database as the source of the table
' alternatively, for strTargetTable, supply a SQL string with
' the external connect string
Set rsFields = db.OpenRecordset(strSourceTable)
For Each fld In rsFields.Fields
strFieldName = fld.Name
If strFieldName <> strJoinField Or (InStr(", " & strExcludeFieldsList _
& ",", strFieldName & ",") <> 0) Then
Select Case fld.Type
Case dbText, dbMemo
strNZValue = "''"
Case Else
strNZValue = "0"
End Select
strSet = " SET " & strTargetTable & "." & strFieldName & " = _
varZLSToNull(" & strSourceTable & "." & strFieldName & ")"
strSet = strSet & ", " & strTargetTable & ".Updated = #" & Date & "#"
strSet = strSet & ", " & strTargetTable & ".UpdatedBy = " _
& STR_QUOTE & strUpdatedBy & STR_QUOTE
strWhere = " WHERE Nz(" & strTargetTable & "." & strFieldName & ", " _
& strNZValue & ") <> Nz(" & strSourceTable & "." & strFieldName _
& ", " & strNZValue & ")"
If db.TableDefs(strTargetTable).Fields(fld.Name).Required Then
strWhere = strWhere & " AND " & strSourceTable & "." _
& strFieldName & " Is Not Null"
End If
If Len(strAdditionalCriteria) > 0 Then
strWhere = strWhere & " AND " & strAdditionalCriteria
End If
Debug.Print strUpdate & strSet & strWhere
Debug.Print SQLRun(strUpdate & strSet & strWhere, dbLocal) & " " _
& strFieldName & " updated."
End If
Next fld
Debug.Print dbLocal.OpenRecordset("SELECT COUNT(*) FROM " _
& strTargetTable & " WHERE Updated=#" & Date & "# AND UpdatedBy=" _
& STR_QUOTE & strUpdatedBy & STR_QUOTE)(0) _
& " total records updated in " & strTargetTable
rsFields.Close
Set rsFields = Nothing
UpdateTableData = True
End Function
try to use the algorithm of sql., the left and right join., then apply it in vb..,
i also have the same problem with you but i try that solution and it works.., on first, it takes almost 3 hours the complete the query but when i apply the sql algo, it just takes few minis