Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2000 Forums
 SQL Server Development (2000)
 Deleleting duplicate records while keeping a single copy

Author  Topic 

AskSQLTeam
Ask SQLTeam Question

0 Posts

Posted - 2006-02-27 : 11:58:55
adefunke writes "Saw the above titled post on 4guysfromrolla.com, and I have the following scenario:

I have two tables, and what I want to do is delete records in the 1st table that don't exist in the 2nd table. However if a records exists x number of times in the 1st table and exists in the 2nd table, I want to keep just one record in the 1st table. How do i determine which record to keep in the 1st table, the one whose id is in the 2nd table. I hope this makes sense.

I tried your query, but it deleted all entries not in the 2nd table from the 1st."

Bex
Aged Yak Warrior

580 Posts

Posted - 2006-02-27 : 12:45:59
I am not sure of the relationships between your tables (whether they are completely identical or have identical columns). However, you can adapt the below example:



--Step 1: create database
CREATE DATABASE Test

USE Test
CREATE TABLE Table1
(
table1ID INT Identity primary key
, data1 CHAR(1)
)

CREATE TABLE Table2
(
table2ID INT Identity primary key
, data2 CHAR(1)
)

--Step 2: Insert some identical values
INSERT INTO Table1(data1)
SELECT 'A'
INSERT INTO Table1(data1)
SELECT 'B'
INSERT INTO Table1(data1)
SELECT 'C'
INSERT INTO Table1(data1)
SELECT 'D'
INSERT INTO Table1(data1)
SELECT 'A'
INSERT INTO Table1(data1)
SELECT 'B'
INSERT INTO Table1(data1)
SELECT 'B'

INSERT INTO Table2(data2)
SELECT 'B'
INSERT INTO Table2(data2)
SELECT 'C'
INSERT INTO Table2(data2)
SELECT 'D'

SELECT * FROM Table1
SELECT * FROM Table2

--Step 3: Remove all the records from Table1 that do not exist in table2
DELETE FROM Table1
WHERE Data1 NOT IN (SELECT Data2 FROM Table2)

SELECT * FROM Table1
SELECT * FROM Table2

--Step 4: Iterate through table1 removing duplicates until only 1 instance remains
DECLARE @count INT
SET @count = 1

WHILE @count > 0
BEGIN
DELETE Table1
FROM Table1
INNER JOIN
(SELECT MAX(table1ID)AS Table1ID FROM table1
INNER JOIN
(SELECT Data1 FROM Table1
GROUP BY Data1
HAVING COUNT(*) > 1) AS T1
ON Table1.Data1 = T1.Data1)AS T2
ON Table1.Table1ID = T2.Table1ID

SET @count = (SELECT @@ROWCOUNT)
END

SELECT * FROM Table1
SELECT * FROM Table2


Hearty head pats
Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2006-02-28 : 01:31:09
Also refer this
http://sqlteam.com/forums/topic.asp?TOPIC_ID=6256

Madhivanan

Failing to plan is Planning to fail
Go to Top of Page
   

- Advertisement -