views:

127

answers:

4

Why does my Do Until loop try to run raw.Delete even though raw.EOF is true? If I have an empty table, this crashes. Why?

Dim raw As Recordset
Set raw = db.OpenRecordset("tblSampleRaw")

If raw.RecordCount > 0 Then
    raw.MoveFirst

    Do Until raw.EOF
        raw.MoveFirst
        raw.Delete
    Loop
End If
A: 

I'm not a VB programmer, but it looks like 'raw' is going to keep dropping through the loop even after it executes 'MoveFirst'.

Chris
A: 

How about Dim raw AS DAO.Recordset?

Remou
+2  A: 

You are doing a Row-By-Agonizing-Row or RBAR (reebar) operation. The larger the table, the more time this is going to take.

Most databases can work more efficiently than RBARs. I suggest you think in terms of SETS rather than rows.

I think you should replace that entire block of code with this:

DoCmd.RunSQL "DELETE * FROM tblSampleRaw"

for purposes of the answer

Dim raw As Recordset
Set raw = db.OpenRecordset("tblSampleRaw")

If raw.RecordCount > 0 Then
    raw.MoveFirst

    WHILE NOT raw.EOF or raw.BOF
        raw.MoveFirst
        raw.Delete
    Loop
End If
Raj More
You are probably right. But a TRUNCATE would even be quicker. I'm just curious why this loop doesn't work though.
Joe Philllips
If you're using Jet/ACE, it processes "DELETE * FROM table" as TRUNCATE.
David-W-Fenton
I think that inside the loop .MoveFirst should be .MoveNext and should be after the Delete.
David-W-Fenton
+1 reeeeeeeeeeeebar!
onedaywhen
@David W. Fenton: What is the * in "DELETE * FROM Table" supposed to do. Delete all columns as opposed to... what?
onedaywhen
+2  A: 

I'm not sure, or a VBA expert, but how come you are constantly doing a MoveFirst? Your never moving forward in the recordset. Try

Do Until raw.EOF
        raw.Delete
        raw.MoveNext
 Loop
Gratzy
Move to first record, delete it, then what is first? The next record I would hope
Joe Philllips
Well if that was true you would never need to do a MoveFirst then would you? You do it initially outside your loop so you should always be on the first record.
Gratzy
Also I don't think you hit EOF until you move passed the last record.
Gratzy
Past of course not passed
Gratzy
you just took the words out of my mouth! +1
Philippe Grondier
The deleted record is not removed from the recordset unless you requery it. You can see this in a continuous or datasheet form in Access if you elsewhere delete a record displaying in the form the record selector and all the controls for that record will remain in the form, but with #DELETED in all the controls.
David-W-Fenton
...but I think this is crazy code to begin with. In the form it's posted, it is completely unjustifiable.
David-W-Fenton
You mean the code to loop through the RS and delete rows? Yes I agree but I think the OP was just looking for an explanation as to why it didn't work.
Gratzy