SQL INSERT but avoid duplicates

前端 未结 6 1002
北荒
北荒 2020-12-31 10:42

I want to do some quick inserts but avoid duplicates into a Table. For argument\'s sake lets call it MarketPrices, I\'ve been experimenting with two ways of doing it but not

6条回答
  •  长情又很酷
    2020-12-31 11:22

    I would go for a semantic solution anytime. Your two proposals seem quite obscure to me (though the latter is better than the former).

    IF NOT EXISTS (
      SELECT 1
      FROM   MarketPrices 
      WHERE  SecurityCode  = @SecurityCode 
             AND BuyPrice  = @BuyPrice 
             AND SellPrice = @SellPrice
    )  
    BEGIN
      INSERT MarketPrices 
        (SecurityCode,   BuyPrice,  SellPrice,  IsMarketOpen)
      VALUES 
        (@SecurityCode, @BuyPrice, @SellPrice, @IsMarketOpen)
    END
    

    With a conglomerate index over SecurityCode, BuyPrice, SellPrice the EXISTS query should go reasonably fast.

    Benchmarking it is a matter of timing a WHILE loop, I would say. Test it and see for yourself.

提交回复
热议问题