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 2008 Forums
 Transact-SQL (2008)
 Inserting Unique values from one row to another

Author  Topic 

jayram11
Yak Posting Veteran

97 Posts

Posted - 2010-09-24 : 16:49:54
I have DRUG_DOSAGE (DRUG_HCPCS, DRUG_DOSAGE) and DRUGSNDC (DRUGNDC_HCPCS, DOSAGE ) tables with 2 variables in each. I want to update DRUG_DOSAGE with records from DRUGSNDC which are not in DRUG_DOSAGE. DRUGSNDC has duplicate values and DRUG_DOSAGE has unique values (PK DRUG_HCPCS)

I tried these 2 methods and bot say PK violation

method1
insert into DRUG_DOSAGE (DRUG_HCPCS, DRUG_DOSAGE)
select distinct(DRUGNDC_HCPCS), DOSAGE
from DRUGSNDC
where DRUGNDC_HCPCS not in (select drug_hcpcs from DRUG_dosage)
and DRUGNDC_HCPCS <> 'N/A'


method 2
INSERT INTO DRUG_DOSAGE (DRUG_HCPCS, DRUG_DOSAGE)
SELECT DRUGNDC_HCPCS, DOSAGE
FROM DRUGSNDC
WHERE NOT EXISTS(SELECT *
FROM DRUG_DOSAGE
WHERE (DRUGSNDC.DRUGNDC_HCPCS = DRUG_DOSAGE.DRUG_HCPCS and
DRUGSNDC.DOSAGE = DRUG_DOSAGE.DRUG_DOSAGE)
) AND DRUGNDC_HCPCS <> 'N/A'


What am i doing wrong?
thaks

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2010-09-24 : 16:58:49
INSERT INTO Table2 (...)
SELECT ...
FROM Table1 t1
WHERE NOT EXISTS (SELECT * FROM Table2 t2 WHERE t1.A = t2.A)

Tara Kizer
Microsoft MVP for Windows Server System - SQL Server
http://weblogs.sqlteam.com/tarad/

Subscribe to my blog
Go to Top of Page

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2010-09-24 : 17:00:03
I forgot to mention your WHERE clause should reflect the PK column(s).

Tara Kizer
Microsoft MVP for Windows Server System - SQL Server
http://weblogs.sqlteam.com/tarad/

Subscribe to my blog
Go to Top of Page

jayram11
Yak Posting Veteran

97 Posts

Posted - 2010-09-24 : 17:46:34
I dont see adiffernece between my query and urs but i still get the error

Violation of PRIMARY KEY constraint 'PK_DRUG_DOSAGE'. Cannot insert duplicate key in object 'DRUG_DOSAGE'.
The statement has been terminated.

(0 row(s) affected)
Go to Top of Page

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2010-09-24 : 18:02:37
I couldn't read your query in all upper case.

Please post the DDL of your tables and some sample data.

Tara Kizer
Microsoft MVP for Windows Server System - SQL Server
http://weblogs.sqlteam.com/tarad/

Subscribe to my blog
Go to Top of Page
   

- Advertisement -