Groups | Blog | Home
all groups > sql server programming > august 2003 >

sql server programming : how to resolve duplicate record issue?


jungewum NO[at]SPAM yahoo.com.au
8/4/2003 10:10:32 PM
I would like to insert into Student table from another database (as
follows).
The problem is I encounter duplicate key (primary key is student_id)
error when inserting the record. How do I change this to perform
insert if record not exist, perform update if record exist?

insert into Student
select * from myserver.mydb.dbo.Student
where register_date >= '2003-01-01 00:00:00'

Thanks in advance
Uri Dimant
8/5/2003 8:24:51 AM
June
I am sure it will help you to start
CREATE TABLE #Demo (
idNo int identity(1,1),
colA int,
colB int
)

INSERT INTO #Demo(colA,colB) VALUES (1,6)
INSERT INTO #Demo(colA,colB) VALUES (1,6)
INSERT INTO #Demo(colA,colB) VALUES (2,4)
INSERT INTO #Demo(colA,colB) VALUES (3,3)
INSERT INTO #Demo(colA,colB) VALUES (4,2)
INSERT INTO #Demo(colA,colB) VALUES (3,3)
INSERT INTO #Demo(colA,colB) VALUES (5,1)
INSERT INTO #Demo(colA,colB) VALUES (8,1)

PRINT 'Table'
SELECT * FROM #Demo

PRINT 'Duplicates in Table'
SELECT * FROM #Demo
WHERE idNo IN
(SELECT B.idNo
FROM #Demo A JOIN #Demo B
ON A.idNo <> B.idNo
AND A.colA = B.colA
AND A.colB = B.colB)

PRINT 'Duplicates to Delete'
SELECT * FROM #Demo
WHERE idNo IN
(SELECT B.idNo
FROM #Demo A JOIN #Demo B
ON A.idNo < B.idNo -- < this time, not <>
AND A.colA = B.colA
AND A.colB = B.colB)

DELETE FROM #Demo
WHERE idNo IN
(SELECT B.idNo
FROM #Demo A JOIN #Demo B
ON A.idNo < B.idNo -- < this time, not <>
AND A.colA = B.colA
AND A.colB = B.colB)

PRINT 'Cleaned-up Table'
SELECT * FROM #Demo

DROP TABLE #Demo

[quoted text, click to view]

AddThis Social Bookmark Button