How to assign SQL MAX(date) to a VBA variable - sql

I am attempting to insert records into a table(cohort) based off of a date(backdate). The backdate variable in VBA should first grab the max date from the SQL query to later be used in the INSERT INTO query in the WHERE clause.
When I attempt to run the function I get a type mismatch error when I try to declare backdate. My code is below.
Dim backdate As Date
Dim sqlString As String
backdate = "SELECT MAX(letter.report_date) " & _
"FROM fadav_letter_recipients as letter ;"
sqlString = "INSERT INTO cohort(person_id, report) " & _
"SELECT letter.person_id, letter.report_type " & _
"FROM fadav_letter_recipients as letter " & _
"WHERE " & backdate & " > letter.report_date;"
DoCmd.RunSQL sqlString
Any help is appreciated

Lookup the value:
backdate = DMax("report_date", "fadav_letter_recipients")
Then format the date value as a date expression:
"WHERE #" & Format(backdate, "yyyy\/mm\/dd") & "# > letter.report_date;"

you get the type mismatch error because you declared backdate as "Date" and you later tried to assign a "string" value to it
There is also a conception error in your code , you need to use a "recordset" object to get what you want
Could you try this code ?:
Dim rec As ado.recordset
Dim sqlString As String
Dim backdate As Date
set rec= currentdb.openrecordset ("SELECT MAX(letter.report_date) " & _
"FROM fadav_letter_recipients as letter ;")
backdate=rec(0)
sqlString = "INSERT INTO cohort(person_id, report) " & _
"SELECT letter.person_id, letter.report_type " & _
"FROM fadav_letter_recipients as letter " & _
"WHERE #" & backdate & "# > letter.report_date;"
DoCmd.RunSQL sqlString

Related

Is it the same to insert into tables from query as from table using VBA?

so this is my code below it works just fine when selecting from a table :
Private Sub cmdStart_Click()
Dim strSql1 As String
Dim strSql2 As String
Dim strSql3 As String
Dim strSql4 As String
Dim qdef As DAO.QueryDef
Dim dbs As DAO.Database
Dim rs As DAO.Recordset
Set dbs = CurrentDb
strSql1 = "insert into qoyod_details (qaed_num,f_year,qaed_date,l_value,Hesab_code) " & _
"select " & Forms("qoyod").qaed_num & " , " & Forms("qoyod").f_year & " , format('" & Forms("qoyod").qaed_date & "' , 'dd/mm/yyyy') , sum(sale_bill_total), 167 " & _
"from sale_bill where sale_bill_date between format( '" & Me.cmbQFrom & "' ,'mm/dd/yyyy') and format( '" & Me.cmbQTo & "' ,'mm/dd/yyyy') and sale_bill_type = 1 "
dbs.Execute strSql1
but when I try to select from a query it just wont work
is there something am doing wrong ?
Thanks in advance.
First you'll need to enclose your data correctly:
numbers need no enclosure: 200
string need to be enclosed with ' or ": 'String' or "String"
Dates need to be enclosed with #: #2020-11-22#
When concatenating strings to an SQL string I usually use the single quotes '
So just guessing on what the field data types are, here is what you SQL string should look like:
strSql1 = "insert into qoyod_details (qaed_num,f_year,qaed_date,l_value,Hesab_code) " & _
"select " & Forms("qoyod").qaed_num & " , " & Forms("qoyod").f_year & " , #" & format(Forms("qoyod").qaed_date, "yyyy-mm-dd") & "#, sum(sale_bill_total) , 167 " & _
"from sale_bill where sale_bill_date between #" & format( Me.cmbQFrom, "yyyy-mm-dd") & "# and #" & format(Me.cmbQTo, "yyyy-mm-dd") & "# and sale_bill_type = 1"
dbs.Execute strSql1
To simplify date conversion use the ISO format yyyy-mm-dd, this will prevent any accidental switching between the day and month in certain configurations.
If you're still getting an error, then try printing the result to the Immediate Window like this for troubleshooting:
Debug.Print strSql1
dbs.Execute strSql1
before trying to execute the string.

MS Access SQL Too Few Parameters: Expected 2

In MS Access 2010, I have the following query which randomly orders the data and puts it in a new sheet. Before I added in the WHERE, it was working, but now I get an error telling me:
Too few parameters: Expected 2.
Does anybody know how I could fix this?
sqlQuery = "SELECT [My_Sheet].* " & _
" INTO My_New_Sheet" & _
" FROM [My_Sheet] " & _
" WHERE [Some_Field] = [Some_Possible_Value_For_The_Field] " & _
" ORDER BY Rnd(-(100000*[Some_Other_Field])*Time())"
Debug.Print sqlQuery
CurrentDb.Execute sqlQuery
Where [Some_Possible_Value_For_The_Field] is comes from [My_Sheet]
Note that this is Access SQL
sqlQuery = "SELECT [My_Sheet].* " & _
" INTO My_New_Sheet" & _
" FROM [My_Sheet] " & _
" WHERE [Some_Field] = '" & [Some_Possible_Value_For_The_Field] & "'" & _
" ORDER BY Rnd(-(100000*" & [Some_Other_Field] & ")*Time())"
Debug.Print sqlQuery
CurrentDb.Execute sqlQuery
When you use a form variable, the value has to be read from outside of the SQL statement. Hence why we close the statement with double quote, add the field value, and then continue by opening the with a double quotes again.
Notice that you need to keep the field qualifiers. In this case I assumed your first field was a string which requires the single quote qualifiers and the second variable as an integer which doesn't require qualifiers.

Update another table when field is changed

I have a form contains "DateProduced" field. The table bound to it is called "Report".
I try to add after update event to this field and want this event to update "DateProduced" field in Quantity table if ID matches for both.
Me![Text0] displays the ID from Report field
Me![Text4] displays the DateProduced from Report field.
The event code is as below.
Private Sub Text4_AfterUpdate()
Dim strSQL As String
strSQL = "UPDATE Quantity " _
& "SET [DateProduced] = (#" & Me![Text4] & "#) " _
& "WHERE ID = (" & Me![Text0] & ")"
DoCmd.RunSQL strSQL
End Sub
But i can not succeed.
That date format will fail for values where dd/mm can be interchanged for a valid date. It should read:
Private Sub Text4_Exit(Cancel As Integer)
Dim strSQL As String
strSQL = "UPDATE Quantity " _
& "SET [DateProduced] = #" & Format(Me!Text4.Value, "yyyy\/mm\/dd") & "# " _
& "WHERE [ID] = " & Me![Text0].Value & ";"
DoCmd.RunSQL strSQL
End Sub
A note: You should change the names of Text0 etc. to meaningful names.
I made it work with the following code. Thx
Private Sub Text4_Exit(Cancel As Integer)
Dim strSQL As String
strSQL = "UPDATE Quantity " _
& "SET [DateProduced] = #" & Format(Me.Text4.Value, "dd-mm-yyyy") & "#" _
& "WHERE [ID] = (" & Me![Text0] & ");"
DoCmd.RunSQL strSQL
End Sub

Update function with case SQL and VBA

I want to try to have a SQL function to update mine table and put a date in the column, I'm using a update function with a case, but I get the error that an operator is missing.
but I can't find the error, does anybody know where it is?
Public Function Add_date( _
ByVal startDate As String, _
ByVal strTableName As String, _
ByVal strFieldName As String, _
ByVal strNummeringField As String) _
As Boolean
Dim strSql As String
strSql = "ALTER TABLE " & strTableName & " ADD " & strFieldName & " date"
DoCmd.RunSQL strSql
strSql = "UPDATE " & strTableName & " SET " & strFieldName & " = CASE WHEN " & strNummeringField & " < 25 THEN '23-07-1991' ELSE '01-01-01' END"
MsgBox strSql
DoCmd.RunSQL strSql
End Function
Jet/ACE (the MS Access db engine) does not support CASE...WHEN. The equivalent for ternary operations is IIF (immediate if). Also, date delimiters are #, not '. Try this instead:
strSql = " UPDATE " & strTableName & _
" SET " & strFieldName & " = " & _
" IIf(" & strNummeringField & " < 25, #23-07-1991#, #01-01-01#)"
Also, you may run into trouble formatting your dates as DD-MM-YYYY, regardless of your regional settings. See International Dates in Access for more information.
One possibility is that the strings representing the table and column name contain invalid characters. Try enclosing them in square brackets:
strSql = "ALTER TABLE [" & strTableName & "] ADD [" & strFieldName & "] date"
DoCmd.RunSQL strSql
strSql = "UPDATE [" & strTableName & "] SET [" & strFieldName & "] = CASE WHEN [" & strNummeringField & "] < 25 THEN '23-07-1991' ELSE '01-01-01' END"

data type mismatch error with OpenRecordSet

Using Access 2007. I'm trying to write a VBA function that will construct a query from the table name, fields, and values that I pass as parameters. I keep getting a "Run-time error '3464': Data type mismatch in criteria expression."
Here's the code:
Function getPrimaryFromForeign(db As Database, table As String, field As String, _
value As Long, _
field2 As String, value2 As Long) As Long
Dim sStr As String
Dim istr As String
Dim rs As Recordset
sStr = "select * from " & table & " where " _
& field & "='" & value & "' and " & field2 & "='" & value2 & "'"
istr = "insert into " & table & "(" & _
field & "," & field2 & ") values ('" & value & "','" & value2 & "')"
Set rs = db.OpenRecordset(sStr)
If rs.RecordCount < 1 Then
db.Execute (istr), dbFailOnError
Set rs = db.OpenRecordset(sStr)
End If
getPrimaryFromForeign = rs("id")
End Function
The error occurs at the line:
Set rs = db.OpenRecordset(sStr)
I think it has something to do with the variable types of Value and Value2. But I've checked them using typename(), and they're both Long when OpenRecordSet() is called. The query is on a table where both of those fields are of type Number. So why is there a type mismatch?
This can occur if you have both DAO and an ADO in you reference library.
In this case declaration order in both your Dim statements and in the references window matters.
1) "You must reference and use both DAO and ADO Recordset objects, dimension the objects explicitly as follows:
Dim adoRS As ADODB.Recordset
Dim daoRS As DAO.Recordset"
2) "Make sure that the reference for the DAO object library has a higher priority in the References dialog box, or clear the reference to Microsoft ActiveX Data Objects."
see Here:
https://support.microsoft.com/en-us/help/181542/you-receive-a-type-mismatch-error-when-you-run-the-openrecordset-metho
I haven't used Access in a long time, but I think that the problem is because you're enclosing Value and Value2 in single quotes in your SQL statement, and not enclosing the fields in the WHERE clause in brackets.
Try it like this:
sStr = "select * from " & table & " where [" _
& field & "] = " & value & " and [" & field2 & "] = " & value2
istr = "insert into " & table & "([" & _
field & "], [" & field2 & "]) values (" & value & "," & value2 & ")"