Author |
Topic |
contec
Starting Member
9 Posts |
Posted - 2006-12-06 : 18:24:45
|
Hi,I currently have two tables, both without primary keys. I need to check one table for existence of 'duplicate' rows (but only dependant on 3 columns, not all) - if a duplicate row exists, I update, if it doesn't exist, I insert.Here's my current 'insert' code - it's quite clunky and ugly I think and there MUST be a way to do this better!INSERT INTO TABLE2(SKU, StoreID, TransactionDate, Qty_OnHand, Qty_Sold, Sales_Amount, Tax)SELECT SKU, StoreID, TransactionDate, Qty_OnHand, Qty_Sold, Sales_Amount, TaxFROM Table1WHERE CAST(SKU AS VARCHAR)+CAST(storeid AS VARCHAR)+CAST(TransactionDate as varchar)NOT IN (SELECT CAST(SKU AS VARCHAR)+CAST(storeid AS VARCHAR)+CAST(TransactionDate as varchar) FROM Table2) Can anyone suggest a better method than this very crude way? |
|
timmy
Master Smack Fu Yak Hacker
1242 Posts |
Posted - 2006-12-06 : 19:26:13
|
A bit cleaner.....INSERT INTO TABLE2(SKU, StoreID, TransactionDate, Qty_OnHand, Qty_Sold, Sales_Amount, Tax)SELECT T1.SKU, T1.StoreID, T1.TransactionDate, T1.Qty_OnHand, T1.Qty_Sold, T1.Sales_Amount, T1.TaxFROM Table1 TI LEFT JOIN Table2 ON T1.SKU = T2.SKU AND T1.storeid = T2.storeid AND T1.TransactionDate = T2.TransactionDateWHERE T2.SKU IS NULL |
 |
|
SwePeso
Patron Saint of Lost Yaks
30421 Posts |
Posted - 2006-12-07 : 03:02:49
|
OrINSERT INTO TABLE2 ( SKU, StoreID, TransactionDate, Qty_OnHand, Qty_Sold, Sales_Amount, Tax )SELECT t1.SKU, t1.StoreID, t1.TransactionDate, t1.Qty_OnHand, t1.Qty_Sold, t1.Sales_Amount, t1.TaxFROM Table1 t1WHERE NOT EXISTS (SELECT * FROM Table2 t2 WHERE t2.SKU = t1.SKU AND t2.StoreID = t1.StoreID AND t2.TransactionDate = t1.TransactionDate) Peter LarssonHelsingborg, Sweden |
 |
|
contec
Starting Member
9 Posts |
Posted - 2006-12-07 : 13:11:29
|
Perfect, thanks. |
 |
|
|
|
|