473,839 Members | 1,361 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Find and delete duplicate records from a table

77 New Member
I am using the following code to find and delete records in a table. The logic will go through each record and if a duplicate row is found will delete it. I ran this code and it worked the first time. Its not deleting the rows when I tried the second time. I debugged the code and its actually going through the delete step but the row is not getting deleted as it did the first time. Please help.

Thanks in advance.
Expand|Select|Wrap|Line Numbers
  1. Function DeleteDuplicates_Click()
  2. On Error Resume Next
  3.  
  4.  Dim db As Database, rst As Recordset
  5.  Dim strDupName As String, strSaveName As String
  6.  Dim strSQL As String
  7.  strSQL = "SELECT [JOBNUM], [trnd] FROM Tableqryduplicates"
  8.  
  9.  Set db = CurrentDb()
  10.  Set rst = db.openrecordset(strSQL, dbOpenSnapshot)
  11.  
  12.  
  13.  If rst.BOF And rst.EOF Then
  14.    MsgBox "No records to process"
  15.  Else
  16.    rst.MoveFirst
  17.    Do Until rst.EOF
  18.      strDupName = rst.Fields("JOBNUM") & rst.Fields("trnd")
  19.  
  20.      If strDupName = strSaveName Then
  21.        rst.Delete
  22.      Else
  23.        strSaveName = rst.Fields("JOBNUM") & rst.Fields("trnd")
  24.      End If
  25.      rst.MoveNext
  26.    Loop
  27.  
  28.    rst.Close
  29.    Set rst = Nothing
  30.    Set db = Nothing
  31.  End If
  32.  
  33.  
  34. End Function
Nov 15 '07 #1
7 9885
Megalog
378 Recognized Expert Contributor
Try adding a rst.edit or rst.delete before any changes, and an rst.update afterwards (before the movenext/loop)? I do pretty much the same thing, except with adding rows, and it needs an addnew/update to stick. I'm assuming it's the same with delete.

And maybe specify your recordset as DAO like:
"Dim db As Database, rst As DAO.Recordset"
Nov 15 '07 #2
NeoPa
32,584 Recognized Expert Moderator MVP
Nice ideas.
I checked out the .Edit & .AddNew and neither is required for a .Delete.
Maybe the DAO.Recordset will help. Explicitly dimming it as DAO would force it to use the methods we are expecting.

AccessHunter, can you let us know if any of this helps at all?
Nov 15 '07 #3
AccessHunter
77 New Member
I used dbOpenDynaset instead of dbOpenSnapshot and it worked.

To me it looked like when I ran this the first time successfully with dbOpenSnapshot, it might have taken a snapshot of the resultant data (after the rows got deleted) and then when I tried 2nd time (with dbOpenSnapshot again) it was looking at that same data !!..not sure about that, its just my assumption. Correct me if I am wrong.

Thanks
Nov 16 '07 #4
NeoPa
32,584 Recognized Expert Moderator MVP
I can't explain why it appears to have worked before. I wouldn't expect it to allow any amendments to a snapshot query. Only a dynamic query should work with deletions as far as I understand.
Nov 16 '07 #5
AccessHunter
77 New Member
Here is my new dilemma, please help me as I am new to VB.
I look at [job nbr], [seq nbr] and [trnd] to detemine if 2 rows are duplicates as per the code below. But I only want to delete a row based on the following logic.

If strDupName = strSaveName Then,

If ptyp(associated with strSaveName) or ptyp(associated with
strDupName) is not Null
If ptyp(associated with strSaveName) is Null,
delete that row,
strSaveName = rst.Fields("cas e nbr") & rst.Fields("seq nbr") &
rst.Fields("trn d")
Get next row.
Else, if ptyp(associated with strDupName) is Null,
delete that row
strSaveName = rst.Fields("cas e nbr") & rst.Fields("seq nbr") &
rst.Fields("trn d")
Get next row
End If
End If

If [p-lnam]+[p-fnam](associated with strSaveName) or [p-lnam]+[p-fnam]
(associated with strDupName) is not Null
If [p-lnam]+[p-fnam](associated with strSaveName) is Null
delete that row
strSaveName = rst.Fields("cas e nbr") & rst.Fields("seq nbr") &
rst.Fields("trn d")
Get next row.
Else, if [p-lnam]+[p-fnam] (associated with strDupName) is Null,
delete that row
strSaveName = rst.Fields("cas e nbr") & rst.Fields("seq nbr") &
rst.Fields("trn d")
Get next row
End If
End If


If [agency-name](associated with strSaveName) or [agency-name](associated
with strDupName) is not Null
If [agency-name](associated with strSaveName) is Null
delete that row
strSaveName = rst.Fields("cas e nbr") & rst.Fields("seq nbr") &
rst.Fields("trn d")
Get next row.
Else, if [agency-name](associated with strDupName) is Null,
delete that row
strSaveName = rst.Fields("cas e nbr") & rst.Fields("seq nbr") &
rst.Fields("trn d")
Get next row
End If
End If

-------------------------------------------------------------------------------------------------------------------

This is the code that works now,


Function DeleteDuplicate s_Click()
On Error Resume Next

Dim db As Database, rst As Recordset
Dim strDupName As String, strSaveName As String
Dim strSQL As String
strSQL = "SELECT [job nbr], [seq nbr], [trnd], [ptyp], [p-lnam], [p-fnam], [agency-name]FROM Tableqryduplica tes"

Set db = CurrentDb()
Set rst = db.openrecordse t(strSQL, dbOpenDynaset)

If rst.BOF And rst.EOF Then
MsgBox "No records to process"
Else
rst.MoveFirst
Do Until rst.EOF

strDupName = rst.Fields("cas e nbr") & rst.Fields("seq nbr") & rst.Fields("trn d")

If strDupName = strSaveName Then
(This is where I want the logic that I just explained above)
rst.Delete
Else
strSaveName = rst.Fields("cas e nbr") & rst.Fields("seq nbr") & rst.Fields("trn d")

End If

rst.MoveNext
Loop

rst.Close
Set rst = Nothing
Set db = Nothing
End If

End Function
-----------------------------------------------------------------------------------------------------------------

Thanks a lot.
Nov 16 '07 #6
Relui
1 New Member
I use this (test.zip unpack and check module). Of course is only a model. From this you can go and develop your solution.
I don't say is the best, a very fancy or the greatest cool solution ... but it works.
I didn't put any comments about author rights but if you mention my name in your solution I realy don't mind ...
Attached Files
File Type: zip Test.zip (33.5 KB, 155 views)
May 30 '16 #7
NeoPa
32,584 Recognized Expert Moderator MVP
Hi.

Just so you know, AccessHunter hasn't been on the site for about seven years now.

There's no issue with posting suggestions or solutions on such an old thread, but you should be aware the original participants are unlikely to benefit from it.

-Adrian (Access MVP and Site Moderator).
May 30 '16 #8

Sign in to post your reply or Sign up for a free account.

Similar topics

1
10810
by: Patrizio | last post by:
Hi All, I've the following table with a PK defined on an IDENTITY column (INSERT_SEQ): CREATE TABLE MYDATA ( MID NUMERIC(19,0) NOT NULL, MYVALUE FLOAT NOT NULL, TIMEKEY INTEGER NOT NULL, TIMEKEY_DTTM DATETIME NULL,
2
7158
by: Barbara | last post by:
Hi, I have an sql database that has the primary key set to three fields, but has not been set as unique(I didn't create the table). I have 1 record that has 2 duplicates and I am unable to delete the duplicate entries. If I try to delete any of the three records(they are identical) I get the message 'key column is insufficient or incorrect. Too many rows were affected by update'. I am trying to do this within Enterprise Mgr. Any...
2
4996
by: ms | last post by:
Access 2000: I am trying to delete duplicate records imported to a staging table leaving one of the duplicates to be imported into the live table. A unique record is based on a composite key of 3 fields (vehicleID, BattID, and ChgHrs). VehicleID and BattID are a TEXT datatype and ChrHrs are a number(long int.) datatype. Since records to be imported can have duplicate records of the composite key I need to clean all but one of the...
7
3907
by: jmstur2 | last post by:
I have a table with what I consider duplicate records. Data in all columns are duplicate except for the date column, meaning that duplicate data was entered on different dates and those dates were stored along with the data. I want to delete the records except for most recent one. I can select the client ID field and the max(date field) to determine the ones I want to keep, but how do I determine the ones to delete. There are often more than...
2
3819
by: farouqdin | last post by:
Hi all i have code which loops through table and deletes the duplicate records. This code does it for one table. How do i change it so it goes through several tables? On Error Resume Next Dim db As DAO.Database, rst As DAO.Recordset Dim strDupName As String, strSaveName As String Set db = CurrentDb()
4
2919
by: ramdil | last post by:
Hi All I have table and it have around 90000 records.Its primary key is autonumber field and it has also have date column and name, then some other columns Now i have problem with the table,as my table contains duplicate entries for a particular date.How can i delete the duplicate entries from the table for that particular column,Now i am doing manually with name column as it will be unique for that date.Can any one help me giving the query...
6
5938
by: Dilip1983 | last post by:
Hi All, I want to delete duplicate records from a large table. There is one index(INDEX_U1) on 4 columns(col1,col2,col3,col4) which is in unusable state. First of all when i tried to rebuild index it showed error as unique key violation. So i want to delete duplicate records for col1,col2,col3,col4 combination. How can i delete the duplicate records from this large table?
1
4098
watertraveller
by: watertraveller | last post by:
Hi all. My ultimate goal is to return two columns, where no single value appears anywhere twice. This means that not only do I want to check that nothing from column A appears in column B and vice-versa, but I also don't want the same value appearing twice in A and twice in B. So far I have: --Diff the columns INSERT INTO @Table SELECT One, Two FROM @Column1 a FULL OUTER JOIN @Column2 b
1
1904
by: DontTell | last post by:
Hi - I am trying to delete duplicate records from a single table. The table has multilple records of duplicate purchase orders. In these instances I need to delete those records that have the same $amt but different qty. I have already created the delete query but am unsure how to specify the criteria which should be based on the $amt and qty. Simply said, I need the code to remove all Duplicates with the same $ but different qty. ...
0
9697
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10909
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10588
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10650
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7019
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5682
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5867
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
4065
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3136
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.