Please help me resolving the error. Error is happening at rs.RecordCount. It looks like out put is not returned to rs. When I tried to check the value in rs.Fields(0).Value, I got "Item cannot be found in the collection corresponding to the requested name or ordinal".
vJobName = "JOBName"
StrQuery = ""
StrQuery = " SET NOCOUNT ON;" + vbCrLf
StrQuery = StrQuery & "DECLARE #vJobStatus Integer;"
StrQuery = StrQuery & " EXEC RDW.dbo.Run_SQL_Job '" & vJobName & "' , #vJobStatus OUTPUT;"
StrQuery = StrQuery & " SELECT #vJobStatus as vJobStatus"
Set rs = cnn.Execute(StrQuery)
If (rs.RecordCount <> 0) Then
vJobStatus = rs.Fields(0).Value
End If
Related
I am using SQL update query in VBA and I am getting the datatype mismatch error. I know that error is basically because of the column spare part. The spare part column contains numeric and alphanumeric values.
Public Function UpdateDistinctColumnFRNumberBasis()
StrInvoiceNumber = "109839-01"
FRSparepartNumber = "FT7119907459"
MergedInvoiceFile = "/test.xlsx"
Dim objConn As Object
Dim objRecordSet As Object
Set objConn = CreateObject("ADODB.Connection")
Set objRecCmd = CreateObject("ADODB.Command")
Set objRecCmd_Update = CreateObject("ADODB.Command")
objConn.Open ("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & _
MergedInvoiceFile & ";Extended Properties=""Excel 8.0;""")
strSQL = " Update [Tabelle1$] SET [Status] = 'Include' Where " & _
"([RECHNR] ='" & StrInvoiceNumber & "' AND [Sparepart] = " & FRSparepartNumber & ")"
objConn.Execute strSQL
objConn.Close
End Function
As commented, the partnumber is text, thus it must be quoted in the SQL:
FRSparepartNumber = "FT7119907459"
' snip
strSQL = "Update [Tabelle1$] SET [Status] = 'Include' Where " & _
"([RECHNR] = '" & StrInvoiceNumber & "' AND " & _
"[Sparepart] = '" & FRSparepartNumber & "')"
This is wrecking my brains for 4 hours now,
I have a Table named BreakSked,
and I this button to update the table with the break end time with this sql:
strSQL1 = "UPDATE [BreakSked] SET [BreakSked].[EndTime] = " & _
Me.Text412.Value & " WHERE [BreakSked].AgentName = " & Me.List423.Value _
& " AND [BreakSked].ShiftStatus = '1'"
CurrentDB.Execute strSQL1
Text412 holds the current system time and List423 contains the name of the person.
I'm always getting this
"Run-time error 3075: Syntax Error (missing operator) in query
expression '03:00:00 am'
Any help please?
EDIT: Thanks, now my records are updating. But now its adding another record instead of updating the record at hand. I feel so silly since my program only has two buttons and I can't figure out why this is happening.
Private Sub Form_Load()
DoCmd.GoToRecord , , acNewRec
End Sub
Private Sub Command536_Click()
strSQL1 = "UPDATE BreakSked SET BreakSked.EndTime = '" & Me.Text412.Value & "',BreakSked.Duration = '" & durationz & "' " & vbCrLf & _
"WHERE (([BreakSked].[AgentID]='" & Me.List423.Value & "'));"
CurrentDb.Execute strSQL1
CurrentDb.Close
MsgBox "OK", vbOKOnly, "Added"
End Sub
Private Sub Command520_Click()
strSql = "INSERT INTO BreakSked (ShiftDate,AgentID,StartTime,Status) VALUES ('" & Me.Text373.Value & "', '" & Me.List423.Value & "', '" & Me.Text373.Value & "','" & Me.Page657.Caption & "')"
CurrentDb.Execute strSql
CurrentDb.Close
MsgBox "OK", vbOKOnly, "Added"
End Sub
You wouldn't need to delimit Date/Time and text values if you use a parameter query.
Dim strUpdate As String
Dim db As DAO.Database
Dim qdf As DAO.QueryDef
strUpdate = "PARAMETERS pEndTime DateTime, pAgentName Text ( 255 );" & vbCrLf & _
"UPDATE BreakSked AS b SET b.EndTime = [pEndTime]" & vbCrLf & _
"WHERE b.AgentName = [pAgentName] AND b.ShiftStatus = '1';"
Debug.Print strUpdate ' <- inspect this in Immediate window ...
' Ctrl+g will take you there
Set db = CurrentDb
Set qdf = db.CreateQueryDef("", strUpdate)
qdf.Parameters("pEndTime").Value = Me.Text412.Value
qdf.Parameters("pAgentName").Value = Me.List423.Value
qdf.Execute dbFailOnError
And if you always want to put the current system time into EndTime, you can use the Time() function instead of pulling it from a text box.
'qdf.Parameters("pEndTime").Value = Me.Text412.Value
qdf.Parameters("pEndTime").Value = Time() ' or Now() if you want date and time
However, if that is the case, you could just hard-code the function name into the SQL and dispense with one parameter.
"UPDATE BreakSked AS b SET b.EndTime = Time()" & vbCrLf & _
As I said in my comment you need to wrap date fields in "#" and string fields in escaped double quotes
strSQL1 = "UPDATE [BreakSked] SET [BreakSked].[EndTime] = #" & _
Me.Text412.Value & "# WHERE [BreakSked].AgentName = """ & Me.List423.Value & _
""" AND [BreakSked].ShiftStatus = '1'"
I currently open and fill a global table with the name ##GlobalTableMain via a macro at the moment. The table gets created the following way:
Public Sub ExecuteSQLQuery(sQuery As String)
Dim cn As New ADODB.Connection
cn.Open strConnection
cn.Execute "SET NOCOUNT ON;" & sQuery
cn.Close
End Sub
The Query roughly looks like this:
CREATE TABLE ##GlobalTableMain (Columns here);
INSERT INTO ##GlobalTableMain (Columns) VALUES
BUNCH OF ROWS
All of this worked just fine until I tried to add another macro that became necessary due to another factor.
The query in question:
Sub AggregateSQLTempTable(sTempTable As String, sAggClm As String)
Dim cn As New ADODB.Connection, rs As New ADODB.Recordset, sQuery As String
Dim selectClms As String, groupClms As String
cn.Open strConnection
sQuery = "SET NOCOUNT ON; SELECT tempdb.sys.columns.name FROM tempdb.sys.columns WHERE tempdb.sys.columns.object_id = Object_Id('tempdb.." & sTempTable & "')"
rs.Open sQuery, cn
sQuery = vbNullString
selectClms = vbNullString
groupClms = vbNullString
If Not (rs.EOF Or rs.BOF) Then
rs.MoveFirst
Do While Not (rs.EOF Or rs.BOF)
selectClms = selectClms & IIf(Len(selectClms) > 0, ", ", "") & IIf(rs!Name = sAggClm, "SUM(" & rs!Name & ") " & rs!Name, rs!Name)
groupClms = groupClms & IIf(rs!Name = sAggClm, "", IIf(Len(groupClms) > 0, ", ", "") & rs!Name)
rs.MoveNext
Loop
sQuery = vbNullString
sQuery = "SELECT * INTO #aggTempTable FROM (SELECT " & selectClms & " FROM " & sTempTable & " GROUP BY " & groupClms & ") a;"
sQuery = sQuery & Chr(10) & "TRUNCATE TABLE " & sTempTable & ";"
sQuery = sQuery & Chr(10) & "INSERT INTO " & sTempTable & " SELECT * FROM #aggTempTable;"
sQuery = sQuery & Chr(10) & "DROP TABLE #aggTempTable;"
cn.Execute sQuery
End If
rs.Close
cn.Close
End Sub
Supposedly SET NOCOUNT ON should prevent this but it doesn't work for me unfortunately.
I've found a solution that helps me do this.
I went ahead and made the Connection a public variable and added the following two macros. Here are all the new macros:
Public cn As New ADODB.Connection
Public Sub OpenSQLConnection()
If Not cn.State = adStateOpen Then cn.Open strConnection
End Sub
Public Sub CloseSQLConnection()
If Not cn.State = adStateClosed Then cn.Close
End Sub
Public Sub ExecuteSQLQuery(sQuery As String)
OpenSQLConnection
cn.Execute "SET NOCOUNT ON;" & sQuery
End Sub
Sub AggregateSQLTempTable(sTempTable As String, sAggClm As String)
Dim rs As New ADODB.Recordset, sQuery As String
Dim selectClms As String, groupClms As String
OpenSQLConnection
sQuery = "SET NOCOUNT ON; SELECT tempdb.sys.columns.name FROM tempdb.sys.columns WHERE tempdb.sys.columns.object_id = Object_Id('tempdb.." & sTempTable & "')"
rs.Open sQuery, cn
sQuery = vbNullString
selectClms = vbNullString
groupClms = vbNullString
If Not (rs.EOF Or rs.BOF) Then
rs.MoveFirst
Do While Not (rs.EOF Or rs.BOF)
selectClms = selectClms & IIf(Len(selectClms) > 0, ", ", "") & IIf(rs!Name = sAggClm, "SUM(" & rs!Name & ") " & rs!Name, rs!Name)
groupClms = groupClms & IIf(rs!Name = sAggClm, "", IIf(Len(groupClms) > 0, ", ", "") & rs!Name)
rs.MoveNext
Loop
sQuery = vbNullString
sQuery = "SELECT * INTO #aggTempTable FROM (SELECT " & selectClms & " FROM " & sTempTable & " GROUP BY " & groupClms & ") a;"
sQuery = sQuery & Chr(10) & "TRUNCATE TABLE " & sTempTable & ";"
sQuery = sQuery & Chr(10) & "INSERT INTO " & sTempTable & " SELECT * FROM #aggTempTable;"
sQuery = sQuery & Chr(10) & "DROP TABLE #aggTempTable;"
cn.Execute sQuery
End If
rs.Close
End Sub
I tested an UPDATE query in Access's query design, and it works, but when I try to use it in my module, I get the error:
Invalid SQL statement; expected... or 'UPDATE'.
My query:
strSql = "UPDATE " & rs.Fields("tableName") & _
" SET " & rs.Fields("foreignKeyName") & " = " & rsContacts.Fields("contactId") & _
" WHERE contactId = " & ContactID
rs: a table that has tableName, foriegnKeyName of the tables to update
rsContacts: a list of contactIds (currently standing on a particular one).
The actual string comes out like this:
UPDATE myTable SET ContactId = 5 WHERE contactId = 2
If the query works, and it is an action query, why am I getting this error?
This is my full code:
Public Sub updateChildTables(ByVal ContactID As Long, ByVal CompanyID As Long)
Dim strSql As String
Dim rs As Recordset
Dim rsPending As Recordset
strSql = "SELECT contactID FROM contacts _
WHERE companyId = " & CompanyID & " and contactId <> " & ContactID
Set rs = CurrentDb.OpenRecordset(strSql)
If Not (rs.BOF And rs.EOF) Then
rs.MoveFirst
strSql = "SELECT * FROM childTables"
Set rsChild = CurrentDb.OpenRecordset(strSql)
rsChild.MoveFirst
Do While Not rsChild.EOF
strSql = "UPDATE " & rsChild.Fields("tableName") & " SET " & rsChild.Fields("foreignKeyName") & " = " & rs.Fields("contactId") & " WHERE contactId = " & ContactID
DoCmd.RunSQL strSql
rs.moveNext
Loop
rsChild.Close
Set rsChild = Nothing
End If
Here is my idea for debugging and possibly even resolving this.
Create a query from within Access normally -- name it UpdateMyTable, for the sake of this example.
Then, rather than using the DoCmd, actually execute this specific query from your VBA.
Dim qry As QueryDef
strSql = "UPDATE " & rsChild.Fields("tableName") & " SET " & _
rsChild.Fields("foreignKeyName") & " = " & _
rs.Fields("contactId") & " WHERE contactId = " & ContactID
Set qry = CurrentDb.QueryDefs("UpdateMyTable")
qry.SQL = strSql
qry.Execute
The big advantage of this is that you can very easily debug this from within Access to both see the rendered SQL and manually run it / tweak it.
I'm getting an error saying that Access cannot find the referenced form CFRRR but there is definitely a form there. Not sure if I'm just not writing the code correctly.
Public Function AssignNullProjects() As Long
Dim db As dao.Database
Dim rs As dao.Recordset
Dim strSQL As String
Set db = CurrentDb
strSQL = "SELECT CFRRRID, [program], [language] FROM CFRRR WHERE assignedto Is Null"
Set rs = db.OpenRecordset(strSQL, dbOpenDynaset)
If Not rs.BOF And Not rs.EOF Then
While Not rs.EOF
strSQL = "UPDATE CFRRR SET assignedto = " & GetNextAssignee & ", assignedby = " & [Forms]![CFRRR]![assignedby] & ", Dateassigned = #" & Now & "#, actiondate = #" & Now & "#, Workername = " & _ [Forms]![CFRRR]![assignedto] & ", WorkerID = " & [Forms]![CFRRR]![assignedto] & " WHERE CFRRRID = " & rs!CFRRRID
db.Execute strSQL, dbFailOnError
rs.MoveNext
Wend
End If
rs.Close
db.Close
Set rs = Nothing
Set db = Nothing
End Function
Public Function GetNextAssignee(program As String, Language As String) As Long
' Returns UserID as a Long Integer with the lowest [TS] value,
' and updates same [TS] by incremented with 1.
Dim db As dao.Database
Dim rs As dao.Recordset
Dim strSQL As String
Set db = CurrentDb
strSQL = "SELECT TOP 1 WorkerID FROM attendance WHERE [Programs] LIKE '*" & program & "*' AND [Language] = '" & Language & "' AND [Status] = '" & Available & "' ORDER BY TS ASC"
Set rs = db.OpenRecordset(strSQL, dbOpenDynaset)
If Not rs.BOF And Not rs.EOF Then
'Found next assignee, update date/time stamp
'strSQL = "UPDATE tblUser SET TS = " & DMax("[TS]", tblUser) + 1 & " WHERE [WorkerID]= " & rs!workerid
strSQL = "UPDATE attendance SET TS = " & DMax("[TS]", "attendance") + 1 & " WHERE [WorkerID]= " & rs!workerid
db.Execute strSQL, dbFailOnError
GetNextAssignee = rs!workerid
Else
'Field TS has NO VALUE FOR ALL RECORDS!
'Code calling this function should check for a return of 0 indicating an error.
GetNextAssignee = 0
End If
rs.Close
db.Close
Set rs = Nothing
Set db = Nothing
End Function