I try to write a query in my Access Project but this runtime error occures in the line, where SQL query is. This is my code:
Private Sub Befehl80_Click()
Dim rst As DAO.Recordset
Set rst = CurrentDb.OpenRecordset("SELECT DISTINCT tb_KonzeptDaten.DFCC, tb_KonzeptDaten.OBD_Code AS Konzept_Obd,tb_KonzeptDaten.DFC INTO Test_Table FROM tb_KonzeptDaten", dbOpenDynaset)
Me.txtDs = rst.RecordCount
End Sub
Would you please tell me how can I solve this problem and why this error occures?
The sql is an action query, it creates a table. You cannot open a recordset from an action query. If you want to run the action query, you can say:
Set db=CurrentDB
ssql="SELECT DISTINCT tb_KonzeptDaten.DFCC, " _
& "tb_KonzeptDaten.OBD_Code AS Konzept_Obd,tb_KonzeptDaten.DFC " _
& "INTO Test_Table FROM tb_KonzeptDaten"
db.Execute ssql, dbFailOnerror
RecordsUpdated=db.RecordsAffected
Related
hi i am trying to insert value into my output table
in my Input table have
profit extra
10 20
when i insert into my output table it should get concatenated as
cost
1020
sub test()
Dim db As DAO.Database
Dim rst As DAO.Recordset
Set db = CurrentDb
db. execut "Insert into OUTPUT_TBL (DESCRIPTION,COST,DEBIT,CREDIT) " & _
" SELECT INPUT.DESCRIPTION,((INPUT.PROFIT)+(INPUT.EXTRA)) AS COST," & _
" IIF(EXTERNAL.SOLUTION='DEBIT',(AMOUNT),0) as DEBIT, " & _
" IIF(EXTERNAL.SOLUTION='CREDIT',(AMOUNT),0) AS CREDIT " & _
" FROM INPUT , EXTERNAL"
db.close
end test
when i try to run it i am getting error as run time error 3075
Couple issues - noticed a typo, it should be db.execute "" not db.execut
Also, for string concatenation use & in Access SQL. 3075 means you used a bad operator.
Another thing, You may also need to add a JOIN to the SQL.
For example, to get you on the right track:
db.execute "Insert into OUTPUT_TBL (DESCRIPTION,COST,DEBIT,CREDIT) SELECT INPUT.DESCRIPTION,((INPUT.PROFIT)&""&(INPUT.EXTRA)) AS COST,IIF(EXTERNAL.SOLUTION='DEBIT',(AMOUNT),0) as DEBIT, IIF(EXTERNAL.SOLUTION='CREDIT',(AMOUNT),0) AS CREDIT from INPUT JOIN EXTERNAL ON INPUT.KEY=EXTERNAL.KEY"
I already have a VBA script that edits this, that, and the other and even opens the table at the end of the script. The only problem is that I want the data I am viewing to be sorted by columnA, and then by columnB.
How do I do that via VBA in Access 2010?
If you just want to see the record set then you could do something like the following:
Dim qdef As Dao.QueryDef
Set qdef = CurrentDb.CreateQueryDef("MyQuery", "SELECT * " & _
"FROM TableName " & _
"ORDER BY columnA, columnB")
DoCmd.OpenQuery "MyQuery"
Then once you are done doing whatever it is you want to do with it you could execute the following to remove the query:
On Error Resume Next
DoCmd.DeleteObject acQuery, "MyQuery"
Or you could do the following:
Dim RSData as DAO.Recordset
Set RSData = CurrentDB.OpenRecordSet("SELECT * " & _
"FROM TableName " & _
"ORDER BY columnA, columnB")
If (RSData.RecordCount > 0) Then
RSData.MoveFirst
Do While RSData.EOF <> True
'HERE YOU CAN WORK WITH EACH FIELD OF THE RECORD INDIVIDUALLY USING
RSData.Fields("columnA").value
RSData.MoveNext
Loop
End If
Then once you are done doing whatever it is you want to do with it you could execute the following:
RSData.Close
Set RSData = Nothing
I have the following VBA code for a .mdb Access file:
If DoCmd.RunSQL "SELECT DISTINCT Max(wk_ending_dt) FROM d2s_loader_performance" < (Date()-Weekday(Date())) Then
DoCmd.RunSQL "DELETE * FROM d2s_loader_performance_tbl WHERE wk_ending_dt = (Date()-Weekday(Date())-35)"
End If
It then highlights the following text: "SELECT DISTINCT Max(wk_ending_dt) FROM d2s_loader_performance" And gives the error Compile Error: Expected Then or GoTo.
Any ideas? I have a Then at the end of my conditional check, and to my understanding the double quotes are just for the SQL syntax. I'm using this If...Then condition to only allow record deletion if the max table date is less than the previous week's ending date.
You probably need to attack it this way:
Dim db as Database
Dim rec as Recordset
Set db = CurrentDB
Set rec = db.OpenRecordset ("SELECT DISTINCT Max(wk_ending_dt) FROM d2s_loader_performance")
If rec(0) < (Date()-Weekday(Date())) Then
DoCmd.RunSQL "DELETE * FROM d2s_loader_performance_tbl WHERE wk_ending_dt = #" & (Date()-Weekday(Date())-35) & "#"
EndIf
I'm assuming that "(Date()-Weekday(Date())-35)" part is supposed to be a calculation, so you need to surround it with ampersands (&), and dates in Access always need to have pound signs (#) before and after them if they're true Date fields.
The problem is that you can execute only action querys with DoCmd.RunSQL. So, you can't execute Select statement. For more info see this
My approach is to using something like this:
Sub SqlExecute()
Dim db As DAO.Database
Dim rsttemp As DAO.Recordset
Set db = CurrentDB
sql = "SELECT DISTINCT Max(wk_ending_dt) FROM d2s_loader_performance"
Set rsttemp = db.OpenRecordset(sql, dbOpenSnapshot)
If rsttemp(0)<(Date()-Weekday(Date())) Then
DoCmd.RunSQL "DELETE * FROM d2s_loader_performance_tbl WHERE wk_ending_dt #=" & (Date()-Weekday(Date())-35) & "#"
End If
Set rsttemp = Nothing
End Function
I have a pivot query I need to loop through and add to another temporary table. The pivot query is a sum of the different statuses found. The statuses are Early, Late, and On-Time. Based on what the user selects, not all of the statuses are present. So when I run the following:
Set rs1 = CurrentDb.OpenRecordset("MyReceivingOnTimeDeliverySummary", dbOpenDynaset)
Set rs = CurrentDb.OpenRecordset("TRANSFORM Sum(recvqty) AS SumOfrecvqty " & _
"SELECT supname, Sum(recvqty) AS TotalReceivedQty " & _
"FROM MyReceivingOnTimeDeliveryDetail " & _
"GROUP BY supname " & _
"PIVOT Status", dbOpenDynaset)
If (rs.RecordCount <> 0) Then
rs.MoveFirst
Do While rs.EOF <> True
rs1.AddNew
rs1.Fields("[supname]").value = rs.Fields("[supname]").value
rs1.Fields("[TotalReceivedQty]").value = rs.Fields("[TotalReceivedQty]").value
rs1.Fields("[Early]").value = rs.Fields("[Early]").value
rs1.Fields("[Late]").value = rs.Fields("[Late]").value
rs1.Fields("[OnTime]").value = rs.Fields("[On-Time]").value
rs1.Update
rs.MoveNext
Loop
End If
If one of the statuses isn't in the results of the query then I will get an error where I am adding that value to the MyReceivingOnTimeDeliverySummary table.
How do I test to for each status and if they are not there then add as 0?
You should be avoiding recordsets for simple operations, like copying with small, uniform changes, in this case. But good news: this makes everything easier!
First, use the SQL statement you already have to create a query.
Dim db As Database
Set db= CurrentDb
db.CreateQueryDef "qry1", "sqltext"
Then, from that query, SELECT INTO (or INSERT INTO) your summary table.
db.Execute "SELECT * INTO MyReceivingOnTimeDeliverySummary FROM qry1"
Then you can add the fields if they aren't there.
On Error Resume Next: db.Execute "ALTER TABLE MyReceivingOnTimeDeliverySummary ADD COLUMN Early NUMBER": Err.Clear: On Error GoTo 0
On Error Resume Next: db.Execute "ALTER TABLE MyReceivingOnTimeDeliverySummary ADD COLUMN Late NUMBER": Err.Clear: On Error GoTo 0
On Error Resume Next: db.Execute "ALTER TABLE MyReceivingOnTimeDeliverySummary ADD COLUMN OnTime NUMBER": Err.Clear: On Error GoTo 0
Finally, fix the nulls to zero.
db.Execute "UPDATE [MyReceivingOnTimeDeliverySummary] SET [Early] = Nz([Early],0)"
db.Execute "UPDATE [MyReceivingOnTimeDeliverySummary] SET [Late] = Nz([Late],0)"
db.Execute "UPDATE [MyReceivingOnTimeDeliverySummary] SET [OnTime] = Nz([OnTime],0)"
Why do it this way? In my experience, SQL is a lot faster than recordsets.
Set the default value to zero for any of the MyReceivingOnTimeDeliverySummary fields which may not be present in the pivot query.
Then loop through the fields in the pivot query recordset and add those fields' values to the matching fields in the other recordset.
Dim fld As DAO.Field
If Not (rs.BOF And rs.EOF) Then
rs.MoveFirst
Do While Not rs.EOF
rs1.AddNew
For Each fld In rs.Fields
rs1.Fields(fld.Name).value = rs.Fields(fld.Name).value
Next
rs1.Update
rs.MoveNext
Loop
End If
Incidentally, you may also find the code operates faster if you substitute dbAppendOnly for dbOpenDynaset here:
OpenRecordset("MyReceivingOnTimeDeliverySummary", dbOpenDynaset)
I'm unsure how much of an impact that change will have. It doesn't change the logic of what you're trying to accomplish. And perhaps any speed impact would be insignificant. But it won't cost you much to find out. :-)
I have an Access Database and I'm using a pass through query to return records from an AS400 table. The connection string and pass through query work fine, but now I'm trying to populate the results of the p-t query into a local table within the db and my code is timing out. This is my first attempt at ADO so I'm disclaiming my code with "I'm not 100% sure what I'm doing!". Could you look at this and see if there is something obvious that I'm doing wrong? Any direction would be appreciated. Thank you in advance.
Sub mod_ADODBConnect()
Const NewTableName = "MyNewTable"
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim db As DAO.Database
Dim sSQL1 As String
Dim sSQL2 As String
sSQL1 = "SELECT ITMNUM, ITMDS, ITPKDS, MJCMCD, SBCMCD, STATUS, PRITIN, OGEXDT from PDBLLIB007.BLPMST07"
sSQL2 = "INSERT INTO ' & NewTableName & ' SELECT [" & sSQL1 & "].* from [" & sSQL1 & "]"
Set cn = New ADODB.Connection
cn.Open "Driver={Client Access ODBC Driver (32-bit)};" & _
"System=DC007; Uid=XXXXX; Pwd=XXXXXX; MgDSN=0; ConnType=2;" & _
"BlockSize=512; MaxFieldLen=2048; LazyClose=1; Prefetch=1; QueryTimeOut=0; Translate=1"
Set rs = New ADODB.Recordset
rs.Open sSQL1, cn, adOpenDynamic, adLockOptimistic
Do While Not rs.EOF
rs.MoveNext
Loop
Set db = CurrentDb
db.Execute ("sSQL2")
rs.Close
cn.Close
Set rs = Nothing
Set cn = Nothing
Set db = Nothing
End Sub
You have a pass-through query which works fine and returns the rows you want. Now you want to store those rows in a new local (Jet/ACE) table. Seems to me a simpler approach would be to use the pass-through as the data source in a new "make table" query.
SELECT * INTO MyNewTable FROM YourPassThruQuery;
Oops, looks like you meant to append those rows to an existing table.
INSERT INTO MyNewTable
SELECT * FROM YourPassThruQuery;
If the table structures don't match, you can use field lists for both tables.
INSERT INTO MyNewTable (fld1, fld2)
SELECT first_field, second_field FROM YourPassThruQuery;