So all I'd like to do is add two queries into a table called tmpGroupSearch. I'm not sure how to do it wit out creating a record set and looping through every record and individually adding them in. I'm thinking there is a much easier way to do this I just can't find the proper structure.
Here are my queries:
"SELECT tblGroupHeader.GroupName" _
& ", tblGroupHeader.GroupNum" _
& ", tblAlsoKnown.AlsoKnown" _
& " FROM tblGroupHeader" _
& " LEFT JOIN tblAlsoKnown ON tblGroupHeader.GroupNum = tblAlsoKnown.GroupNum" _
& " WHERE tblGroupHeader.GroupName like '" & txtgroupSearch.Value & "*'" _
& " OR tblGroupHeader.GroupNum like '" & txtgroupSearch.Value & "*';"
"Select * FROM tblActionLog WHERE AlsoKnown LIKE '" & txtgroupSearch.Value & "*';"
You can follow an INSERT INTO clause with a list of values, like #Asad shows, or also a SELECT query. Do yourself a favor and always list the field names in your SQL or you are just creating time bombs for the future.
Dim strSelect1 As String
Dim strSelect2 As String
strSelect1 = "SELECT tblGroupHeader.GroupName" _
& ", tblGroupHeader.GroupNum" _
& ", tblAlsoKnown.AlsoKnown" _
& " FROM tblGroupHeader" _
& " LEFT JOIN tblAlsoKnown ON tblGroupHeader.GroupNum = tblAlsoKnown.GroupNum" _
& " WHERE tblGroupHeader.GroupName like '" & txtgroupSearch.Value & "*'" _
& " OR tblGroupHeader.GroupNum like '" & txtgroupSearch.Value & "*';"
strSelect2 = "Select * FROM tblActionLog WHERE AlsoKnown LIKE '" & txtgroupSearch.Value & "*';"
Dim strInsert1 As String
Dim strInsert2 As String
strInsert1 = "INSERT INTO tmpGroupSearch (GroupName, GroupNum, AlsoKnown) " & strSelect1
'the next version is valid SQL, but *dangerous* because field names are not enumerated
strInsert2 = "INSERT INTO tmpGroupSearch " & strSelect2
It is possible to write the INSERT INTO statement in two forms.
The first form does not specify the column names where the data will be inserted, only their values:
INSERT INTO table_name
VALUES (value1,value2,value3,...);
The second form specifies both the column names and the values to be inserted:
INSERT INTO table_name (column1,column2,column3,...)
VALUES (value1,value2,value3,...);
Test this parameter query in the Access query designer and adjust as needed so that it returns the row set you expect for the pSearchText parameter value you supply.
PARAMETERS pSearchText Text ( 255 );
SELECT gh.GroupName, gh.GroupNum, ak.AlsoKnown
FROM
tblGroupHeader AS gh
LEFT JOIN tblAlsoKnown AS ak
ON gh.GroupNum = ak.GroupNum
WHERE
gh.GroupName Like "'" & pSearchText & "*'"
OR gh.GroupNum Like "'" & pSearchText & "*'"
UNION ALL
SELECT al.GroupName, al.GroupNum, al.AlsoKnown
FROM tblActionLog AS al
WHERE al.AlsoKnown Like "'" & pSearchText & "*'"
Once you have it returning the correct data, convert it to an INSERT query by changing the beginning of the statement to this ...
PARAMETERS pSearchText Text ( 255 );
INSERT INTO tmpGroupSearch (GroupName, GroupNum, AlsoKnown)
SELECT gh.GroupName, gh.GroupNum, ak.AlsoKnown
... and the rest
Save that query as qryGroupSearchAppend. Then you can execute that query from your VBA code:
Dim qdf As DAO.QueryDef
Set qdf = CurrentDb.QueryDefs("qryGroupSearchAppend")
qdf.Parameters("pSearchText").Value = Me.txtgroupSearch.Value
qdf.Execute dbFailOnError
Related
I have a textbox [ScanItem] on a Split Form that take two different barscan values, Works Really Slick!
Alphanumeric, Len 11
Numeric, Len 12
My Update Query works, but for only one WHERE Condition. I was hoping to use the Len function to combine the WHERE function's but can't get it to work.
Update Query for Alphanumeric Len 11 (Example: 019-WMD-001 ):
strSQL = "UPDATE [Location Table]" & _
"SET [Location]='" & Me.Location1.Value & "'" & _
"WHERE [Location Table].[Custom Label] = [ScanItem]"
Update Query for Numeric Len 12
"WHERE [Location Table].[Item ID] = [ScanItem]"
I understand the table spaces are a no-no but I do not have control over that. If this will not work, any other solution would be welcomed.
If I understand your question correctly you want to apply one WHERE clause evaluation if length of [ScanItem] = 11 (in which case use [Custom Label] in comparison) and another WHERE clause evaluation if length of [ScanItem] = 12 (in which case use [Item ID] in comparison). There are multiple ways to do this. I'm not addressing SQL injection issue--just the query logic, but you can always rewrite this using parameters (recommended best practice). You could write the query to use conditional logic or your vba could use the conditional logic (assuming there are only possible length conditions of 11 and 12). I'm a fan of scenario 2.
Scenario 1 (query uses conditional logic):
strSQL = "UPDATE [Location Table] " & _
"SET [Location]='" & Me.Location1.Value & "' " & _
"WHERE ([Location Table].[Custom Label] = '" & Me.ScanItem.Value & "' AND LEN('" & Me.ScanItem.Value & "') = 11) " & _
" OR ([Location Table].[Item ID] = '" & Me.ScanItem.Value & "' AND LEN('" & Me.ScanItem.Value & "') = 12)"
Scenario 2 (vba uses conditional logic--assuming only 2 possible lengths of 11 and not 11):
strSQL = "UPDATE [Location Table] " & _
"SET [Location]='" & Me.Location1.Value & "' " & _
"WHERE ([Location Table]." & IIF(Len(Me.ScanItem.Value)=11,"[Custom Label]","[Item ID]") & " = '" & Me.ScanItem.Value & "'"
For the first WHERE condition, you've handled it with string concatenation.
For the second one, however, you're just referring to the field.
A solution using string concatenation (at risk for SQL injection):
strSQL = "UPDATE [Location Table]" & _
" SET [Location]='" & Me.Location1.Value & "'" & _
" WHERE [Location Table].[Custom Label] = '" & Me.ScanItem.Value & "'"
A more proper solution using parameters:
strSQL = "UPDATE [Location Table]" & _
" SET [Location]= paramLocation" & _
" WHERE [Location Table].[Custom Label] = paramLabel"
Set qdf = CurrentDb.CreateQueryDef("", strSQL)
qdf.Parameters("paramLocation").Value = Me.Location1.Value
qdf.Parameters("paramLabel").Value = Me.ScanItem.Value
qdf.Execute
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
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.
We'd like to count from an Access database that has multiple tables - about 50.
We need to count from 1 column in each table that is 'QCPASS' This is a check box - if a product passed the box was checked if failed then not. We need to count both for EACH table, also allowing the user to specify a date range from a date column that exists in every table.
I've tried this with a query but I am told the query is unable to select, count and do the date range. Any VBA help would be great.
Exporting to Excel would be great, but any results would be fine. Here is the query I created that counts in a column from each table passes and failures. I can't iterate with a query either, so VBA seems the way to go:
SELECT "Table1" , Count('qcpass') AS column
FROM 5000028
GROUP BY [5000028].qcpass
union
SELECT "Table2",count('qcpass')
FROM 5000029
Group By [5000029].qcpass;
You can traverse the full TableDefs collection in your database, and create a query using VBA.
A word of warning: The TableDefs collection has the Access database system tables, so you need to skip this. A way I suggest you is to check for a specific table name prefix (it is noted in the code below).
public sub createMyBigUnionQuery()
dim db as DAO.database(), tbl as DAO.tableDef
dim strSQL as string, i as integer
set db = currentdb()
i = 1
for each tbl in db.TableDefs
if left(tbl.name, 1) = "5" then ' Check for a table name prefix
if i = 1 then
' The final spaces are important
strSQL = "select '" & tbl.Name & "' as table, count(qcpass) as column " & _
"from [" & tbl.Name & "] " & _
"group by qcpass "
else
' The final spaces are important
strSQL = strSQL & " union all " & _
"select '" & tbl.Name & "' as table, count(qcpass) as column " & _
"from [" & tbl.Name & "] " & _
"group by qcpass "
end if
i = i + 1
end if
next tbl
db.createQueryDef "qryYourFinalQuery", strSQL
db.close
exit sub
Notice that you can define any valid query you want. Take this as a hint, and tweak it to fit your specific needs.
Hope this helps you
Adressing #HansUp comment, if you need to filter your data by date, you have two options:
Include the where condition on every select created by the procedure
Include the date field in your query and group by it, and create a second query to filter the data you need from the created query.
I would personally go with option 1, and here is a sample code:
public sub createMyBigUnionQueryWithDates(d0 as date, d1 as date)
dim db as DAO.database(), tbl as DAO.tableDef
dim strSQL as string, i as integer
set db = currentdb()
i = 1
for each tbl in db.TableDefs
if left(tbl.name, 1) = "5" then ' Check for a table name prefix
if i = 1 then
' The final spaces are important
strSQL = "select '" & tbl.Name & "' as table, count(qcpass) as column " & _
"from [" & tbl.Name & "] " & _
"where rowDate between " & cDbl(d0) & " and " &cDbl(d1) & " " & _
"group by qcpass "
else
' The final spaces are important
strSQL = strSQL & " union all " & _
"select '" & tbl.Name & "' as table, count(qcpass) as column " & _
"from [" & tbl.Name & "] " & _
"where rowDate between " & cDbl(d0) & " and " &cDbl(d1) & " " & _
"group by qcpass "
end if
i = i + 1
end if
next tbl
db.createQueryDef "qryYourOtherFinalQuery", strSQL
db.close
exit sub
The reason I use cDbl(d0) is because Access dates are sensitive to regional settings, and I've had a lot of headaches dealing with it. Access (and many other Microsoft products) store dates as floating-point numbers (the integer part is the date, and the decimal part is the time).
Another word of warning: If your dates don't include time, then the between condition will work. But if they do include time, then I recommend you change the where condition to this:
"where rowDate >= " & cDbl(d0) & " and rowDate < " & cDbl(d1 + 1)"
I've done this a zillion times, and I don't know what's changed.
Private Sub Foo()
dim rst as DAO.Recordset
set rst = CurrentDB.OpenRecordset("Select * From Table1;", dbOpenDynaset)
rst.movefirst
Do Until rst.EOF
DoCmd.RunSQL INSERT INTO Table2 (Last, First, Gender) VALUES (" & "' & rst!Last & '" & ", " & "' & rst!First & '" & ", " & "' & rst!Gender & '" & ");"
rst.MoveNext
Loop
End Sub
If I do this, the values inserted into Last, First and Gender are '" & rst!ColumnName & "' versus the actual data from the column.
If I omit the single quotes it works until it comes across a last name with a hypen or aposttrophe and then it throws a syntax error.
But I've done this same thing in code a zillion times the last 6 years and it's always worked and for whatever reason on this new project it's not proving the results I am used to.
Any ideas?
You seem to have that a bit mixed up:
DoCmd.RunSQL "INSERT INTO Table2 (Last, First, Gender) VALUES ('" & _
& rst!Last & "', '" & rst!First & "', '" & rst!Gender & "');"
Note that if you have names that contain apostrophes, the above will fail, so it is a good idea to escape them like so:
DoCmd.RunSQL "INSERT INTO Table2 (Last, First, Gender) VALUES ('" & _
& Replace(rst!Last,"'","''") & "', '" & Replace(rst!First,"'","''") _
& "', '" & rst!Gender & "');"
The other point that I wonder about is why are you doing this in steps? Why not:
strSQL = "INSERT INTO Table2 (Last, First, Gender) " _
& "SELECT Last, First, Gender FROM Table1 "
CurrentDB.Execute strSQL, dbFailOnError