Reputation: 51
I'm trying to do a bulk insert (SQL Server 2008) into a table but the insert must ignore any duplicate already in the table.
The simplified table will look like this with existing values.
TBL_STOCK
id | Stock
---------------
1 | S1
2 | S2
3 | S3
Now I want to do a bulk insert that looks like
INSERT INTO TBL_STOCK (Id, Stock)
VALUES
(3, S3),
(4, S4),
(5, S5)
This works but will cause duplicate entries
How do I go about ignoring duplicate entries in the Stock
column?
Upvotes: 3
Views: 5277
Reputation: 241
By "ignoring duplicate entries", you mean avoiding them in TBL_STOCK, right ?
I might be a bit late, but have you tried the following:
INSERT INTO #TempStock (Id, Stock) -- temporary table
VALUES
(3, S3),
(4, S4),
(5, S5)
INSERT INTO TBL_STOCK
SELECT * FROM #TempStock
WHERE NOT EXISTS (SELECT Stock FROM #TempStock WHERE #TempStock.Stock = TBL_STOCK.Stock)
DROP TABLE #TempStock
Upvotes: 0