Executing a SQL query from vba results with nothing - sql

Cheers,
I am trying to send a simple SQL query, but I get no results in my recordset as if it simply was not executed.
Just after, I am executing a different query, which results correctly.
When running the same query from SMSS, do brings up the desired results.
Following is the code:
If CheckLogsFromRestartDay = True Then
'This line does NOT seem to work. Nothing is changed in the Recordset
Set objMyRecordset = objMyConn.Execute( _
" SELECT top 1 cast(tValue AS date) AS RestartDate " & _
" FROM settings (nolock) WHERE tkey = 'EngineStartTime' ")
'This line DOES provide an answer correctly
Set objMyRecordset = objMyConn.Execute( _
" SELECT * FROM " & LogTable & " (nolock) where Webpage like 'Engines%'" & _
" ORDER BY id desc")
sTodayMMDD = objMyRecordset!RestartDate
Else
sTodayMMDD = Format(Date, "yyyy-mm-dd")
End If

Related

OpenRecordset not returning usable recordset / .edit not working?

Working on a database on Access, trying to run a query to find a record with the latest date and a 'where' condition.
Error returned is "Run Timer Error '3027' Cannot update. Database or object is read-only"
Following conditions:
Button is clicked on a form that contains a text field for 'fCheckInFor'.
Database 'ToolTests' fields
"CheckOut" is dates in format of "3/15/2019 5:35:31 PM"
"CheckIn" is dates in format of "3/15/2019 5:35:31 PM"
"CheckInFor" is a text field
"ToolNumber" is a text field
Public CheckInTool as String
Private Sub CheckIn_Click()
CheckInTool = "000"
If Me.fCheckInFor = "" Then
MsgBox "Enter Returning User."
Else
Dim dbsUE As DAO.Database
Dim rstUE As DAO.Recordset
Set dbsUE = CurrentDb
Set rstUE = dbsUE.OpenRecordset("SELECT Max([CheckOut]) FROM [ToolTests] WHERE [ToolNumber]= '" & CheckInTool & "'")
With rstUE
.Edit 'error occurs here
!CheckIn = Now()
!CheckInFor = Me.fCheckInFor
.Update
End With
MsgBox "Checked In"
DoCmd.Close acForm, "CheckIn"
End If
End Sub
So the error throws at the .Edit line, I'm unsure where to go from here. would also be fine with tossing the whole thing and going at it from a different direction.
If I get you right, you want to update a record that has a specific ToolNumber. So, if you want to use a subquery, you will either need to use that criterion in both the main query and the subquery, or link the subquery with the main query using that field:
Set rstUE = dbsUE.OpenRecordset( _ &
"SELECT CheckIn, CheckinFor FROM ToolTests WHERE" & _
" CheckOut IN (SELECT Max(CheckOut) FROM ToolTests AS tmp WHERE ToolNumber = ToolTests.ToolNumber)" & _
" And ToolNumber = '" & CheckInTool & "'")
Alternatively, you could simply sort the records in the correct order and update the first one:
Set rstUE = dbsUE.OpenRecordset( _ &
"SELECT CheckIn, CheckinFor FROM ToolTests WHERE" & _
" ToolNumber = '" & CheckInTool & "'" & _
" ORDER BY CheckOut DESC")

MS Access - Execute SQL statement receives error

I get an error:
"Object doesn't support this property or method"
...when I try to run this code:
Dim db As DAO.Database
Dim mySQL As String
Set db = currentdb
mySQL = "SELECT tbl1.pID, tbl1.sID, tbl1.Type, tbl1.Description, tbl1.Amount, tbl1.Delete, tbl1.Approve, tbl2.sName FROM tbl2 INNER JOIN tbl1 ON tbl2.sID = tbl1.sID WHERE pID = " & Forms.frmEdit1.cboP & " And Delete = False;"
db.Execute mySQL, dbFailOnError
Set db = Nothing
It seems like the error is somewhere in the last line (that's where it fails when I use the immediate window) I also tried the single quotes around 'False'.
EDIT: Recordsource that worked
SELECT tbl1.[pID],
tbl1.[sID],
[tbl1].Type,
[tbl1].Description,
[tbl1].Amount,
[tbl1].Delete,
tbl1.Approve,
tbl2.sName
FROM tbl2 INNER JOIN tbl1 ON tbl2.sID = tbl1.sID
WHERE pID = Forms![frmEdit1].cboP
And [Delete] = False;
Logically, sending a SELECT statement to Execute is saying, 'select values according to this criteria but don't let me know the results', which doesn't make much sense. Populating an unbound subform needs to be done manually - that's what makes it 'unbound':
Sub LoadByID(Optional ByVal ID)
Dim RS As DAO.Recordset, SQL As String
If IsMissing(ID) Then ID = Forms!frmEdit1.cboP
SQL = " SELECT tbl1.sID, tbl1.Type, tbl1.Description, " + _
" tbl1.Amount, tbl1.Delete, tbl1.Approve, tbl2.sName " + _
" FROM tbl2 INNER JOIN tbl1 ON tbl2.sID = tbl1.sID " + _
" WHERE pID = " & ID & " And [Delete] = False;"
Set RS = CurrentDb.OpenRecordset(SQL)
' Assuming no match is an error; if it isn't, rewrite accordingly
If RS.EOF Then Err.Raise 999, "LoadByID", "Er, no selection..."
txtID.Value = RS!ID
txtDescription.Value = RS!Description
' and so on...
End Sub
I've allowed specifying the ID not through the combo box to make the method easier to test. Also, note that if the form is supposed to allow editing, then you will need more code to then save any changed values.
Edit
The above was assuming only one return record. If more than one, loop like this:
Sub LoadByID(Optional ByVal ID)
Dim RS As DAO.Recordset, SQL As String
If IsMissing(ID) Then ID = Forms!frmEdit1.cboP
SQL = " SELECT tbl1.sID, tbl1.Type, tbl1.Description, " + _
" tbl1.Amount, tbl1.Delete, tbl1.Approve, tbl2.sName " + _
" FROM tbl2 INNER JOIN tbl1 ON tbl2.sID = tbl1.sID " + _
" WHERE pID = " & ID & " And [Delete] = False;"
Set RS = CurrentDb.OpenRecordset(SQL)
' add code to clear current display here...
While Not RS.EOF
' add code to load the individual values here...
RS.MoveNext
Wend
End Sub

New ODBC issue Access 2007

I have an MS Access 2007 front end to a MS SQL Server 2008R2 back end.
I've got a query that's part of a loop, and it's suddenly started generating Run-time error '3146': ODBC--call failed. errors on one query as the loop itterates. Oddly, it's not the first iteration. EDIT: When I say suddenly, it's been running like this just fine for several months (probably since March).
Set db = CurrentDb
db.QueryTimeout = 480 'thought there was a timeout issue, so set this very high
Set SupvRS = db.OpenRecordset("SELECT DISTINCT tblProcessors.Supervisor, tblProcessors.SupervisorEmail " & _
" FROM tblProcessors INNER JOIN (tblAuditPr INNER JOIN tblAuditPr_A ON tblAuditPr.PrAudit_ID = tblAuditPr_A.PrAudit_ID)" & _
" ON tblProcessors.Processor = tblAuditPr_A.Processor" & _
" WHERE tblProcessors.Supervisor IS NOT NULL " & _
" AND tblAuditPr.EndDate BETWEEN " & GetSQLDate(Me.txtFrom) & " AND " & GetSQLDate(Me.txtTo) & _
" AND tblProcessors.Processor<>'Default Processor' " & _
" AND tblAuditPr_A.Answer Not In ('NA','NF')" & _
" AND tblAuditPr.Status = 'Submitted'")
Do While Not SupvRS.EOF
'Send Supervisor Email
Attachment = PARG.GenerateAuditReport(SupvRS.Fields("Supervisor"), parSupervisor, Me.txtFrom, Me.txtTo)
Set EmailRS = db.OpenRecordset("SELECT * FROM tblProcessors WHERE Supervisor = " & GetSQLString(SupvRS.Fields("Supervisor")))
If EmailRS.EOF Then
Err.Raise -234923, Description:="Cannot find tblProcessors record for " & SupvRS.Fields("Supervisor") & "."
End If
If IsNull(EmailRS.Fields("SupervisorEmail")) Then
MailTo = <redacted>
Else
MailTo = EmailRS.Fields("SupervisorEmail")
End If
Set EmailRS = Nothing
Mailer.AddMailDocument MailTo:=MailTo, _
Subject:=Subject, _
Body:=Body, _
Attachments:=Attachment, _
From:=<redacted>
'Iterate processor emails if requested.
If Me.chkProcessor Then
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'----------------------------------------------------------------------------------------
'ERROR occurs here, but only after several supervisors have successfully passed through
Set ProcRS = db.OpenRecordset("SELECT DISTINCT tblProcessors.Processor, tblProcessors.ProcessorEmail FROM tblAuditPr" & _
" INNER JOIN (tblProcessors INNER JOIN tblAuditPr_A ON tblProcessors.Processor = tblAuditPr_A.Processor) " & _
" ON tblAuditPr.PrAudit_ID = tblAuditPr_A.PrAudit_ID" & _
" WHERE tblProcessors.Supervisor = " & GetSQLString(SupvRS.Fields("Supervisor")) & _
" AND tblAuditPr.EndDate BETWEEN " & GetSQLDate(Me.txtFrom) & " AND " & GetSQLDate(Me.txtTo))
'----------------------------------------------------------------------------------------
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Do While Not ProcRS.EOF
If Not IsNull(ProcRS.Fields("ProcessorEmail")) Then
On Error Resume Next
Attachment = PARG.GenerateAuditReport(ProcRS.Fields("Processor"), parProcessor, Me.txtFrom, Me.txtTo)
If Attachment <> "" Then
MailTo = ProcRS.Fields("ProcessorEmail")
Mailer.AddMailDocument MailTo:=MailTo, _
Subject:=Subject, _
Body:=Body, _
Attachments:=Attachment, _
From:=<redacted>
Else
Err.Clear
End If
On Error GoTo 0
End If
ProcRS.MoveNext
Loop
Set ProcRS = Nothing
End If
SupvRS.MoveNext
Loop
As noted in the code, the error occurs on an inner loop that successfully executes for other supervisors. It does consistantly break on one particular individual. Using the GetSQLString and GetSQLDate functions (returns ' delimited, double '' when necessary, pretty strings, and # delimited dates, respectivly, for passing Access queries through to SQL Server) in break mode, I duplicated the exact query that was giving me problems in an Access query. It returned a timeout error, but changing the database default timeout (and closing/opening the db) didn't resolve the issue. I pasted the exact same query into SSMS (replacing the # date delimiters with ') and it executed just fine there (taking about 1:30-2:00 to execute each try).
Taking a pause in typing up this post, I put some error trapping in to see if I could get the actual error message SQL Server was returning, when it ran without error. To me, that indicates that it is likely a time out issue. Anyone have a more educated guess as to what it actually is, or a suggestion on how to make the query more efficient so it doesn't time out?

SQL Error Access 2010 VBA Update Command

I need help figuring out an error in my SQL statement. I have been trying several things, but nothing seems to work?
This is the error message I receive
Run-time error '3075':
Syntax error (missing operator) in query expression '([description] = Manufacturing and Delivery Schedule AND [pr_num] = 83)'.
This is my code:
Private Sub Command6_Click()
' ===================================================
' Receives the selected item in the combo box
' ===================================================
' Open the Database connection
Dim data_base As Database
Set data_base = CurrentDb
' Grab description and pr number from the form
Dim desc As string
dim pr_number as long
desc = Combo4.Value
pr_number = Text8.Value
' Build the query
Dim query As String
query = "UPDATE VDR_Table " & _
"SET [received] = [p1] " & _
"WHERE ([description] = " & desc & _
" AND [pr_num] = " & pr_number & ");"
Dim rec_set As DAO.Recordset
Set rec_set = data_base.OpenRecordset(query)
' Build the QueryDef
Set qd = data_base.CreateQueryDef("")
qd.SQL = query
' Execute query
qd.Parameters("p1").Value = true
qd.Execute
' Close nad null record set
rec_set.close
set rec_set = nothing
' Close the connection to the database
data_base.Close
' Prompt the user success
MsgBox "Item has been received"
End Sub
Thanks in advance for any help!
You need to enclose the description field value you are setting in quotes since it is a string field. It should look like this:
' Build the query
Dim query As String
query = "UPDATE VDR_Table " & _
"SET [received] = [p1] " & _
"WHERE ([description] = '" & desc & _
"' AND [pr_num] = " & pr_number & ");"
Removed the links below since they don't matter in this case.
Also, I would recommend using parameters instead of string concatenations to avoid SQL injections. Here's an example of using parameters with VBA - http://support.microsoft.com/kb/181734 - and here is some reasoning on why to use parameterized sql - http://www.codinghorror.com/blog/2005/04/give-me-parameterized-sql-or-give-me-death.html.

Select statement includes a reserved word or an argument name that is misspelled or missing or punctuation is incorrect

I cannot for the life of me figure out why I am getting this error. I am pretty familiar with VB and SQL but am not used to using Access. I have ran my query separately just in access and it works just fine... Below is my code. Any suggestions!?!? Thanks so much!!!
Private Sub Command18_Click()
Dim db As Database
Dim rs As Recordset
Dim sSQL As String
sSQL = "SELECT Count(*) AS Duration" _
& "FROM [Project_Duration_Info] " _
& "WHERE [Project - Consulting Partner] In (Select [CP_Name] from [CP's] " _
& "Where [CP_DDL] = [Forms]![Consulting Partners]![CPs]) " _
& "AND [Project - Actual Complete Date] >= [Forms]![Consulting Partners]![FromDate] " _
& "AND [Project - Actual Complete Date] < [Forms]![Consulting Partners]![ToDate]"
Set db = CurrentDb
Set rs = db.OpenRecordset(sSQL)
If rs.RecordCount > 0 Then
Me.Duration = rs!Durations
Else
Me.Duration = ""
End If
Set rs = Nothing
Set db = Nothing
End Sub
It looks like you are combining VBA and SQL into one statement: [Forms]![Consulting Partners]![CPs] appears to be a variable pulled from the form but embedded within the SQL try
WHERE [CP_DDL] = '" & [Forms]![Consulting Partners]![CPs] & "'
The same logic will need to be applied to the [Forms]![Consulting Partners]![ToDate] and [Forms]![Consulting Partners]![FromDate] and if these are dates you'll probably need to surround them with # (so end result would be #01/01/2012#)