views:

37

answers:

1

how does one insert records from one table to another that has a unique index in the destination table without going through the insert and then removal of duplicates by deleting the index?

INSERT INTO forms(url,feedUrl, dateadded)
SELECT url, feedurl, dateadded
FROM Book3 T2
where not exists(select * from forms T1 where T1.url = T2.url;
T2.feedurl = T1.feedUrl and  T2.dateadded =T1.dateadded) 

Violation of UNIQUE KEY constraint 'IX_forms'. Cannot insert duplicate key in object 'dbo.forms'.

Table forms

CREATE TABLE [dbo].[forms](
[id] [int] IDENTITY(1,1) NOT NULL,
[url] [varchar](450) NULL,
[feedUrl] [varchar](450) NULL,
[dateadded] [datetime] NULL,
 CONSTRAINT [PK_forms] PRIMARY KEY CLUSTERED 
 (

Table book3

CREATE TABLE [dbo].[Book3](
[url] [varchar](450) NULL,
[feedurl] [varchar](450) NULL,
[dateadded] [datetime] NULL
) ON [PRIMARY]
+2  A: 

You may have duplicates in your results set. Does this query give you fewer records than the orginal select?

SELECT distinct url, feedurl, dateadded 
FROM Book3 T2 
where not exists(select * from forms T1 where T1.url = T2.url 
T2.feedurl = T1.feedUrl and  T2.dateadded =T1.dateadded)  
HLGEM
actually it does 1195429 vs original select 1195785I thought I deleted all the dupes...let me try again. thanks
vbNewbie
darn it. I just deleted my table. Thanks for the help. Jsut for the record the above statment should work if there werent any dupes right?
vbNewbie
If there are duplicates in your source table then you'll need to GROUP BY or use DISTINCT to eliminate those duplicates. How you do that will depend on your business rules for defining a duplicate and which one to keep. Assuming that you want distinct url, feedurl values, do you use the latest dateadded? The first? Etc.
Tom H.
first dateadded...but it does not matter right now as long as the duplicates are removed. Thank you. How do give u a useful or answer tick.
vbNewbie