SQL INSERT pero evita duplicados
Quiero hacer algunas inserciones rápidas pero evitar duplicados en una tabla. Por el bien de los argumentos, llamémoslos MarketPrices, he estado experimentando con dos formas de hacerlo pero no estoy seguro de cómo comparar que será más rápido.
INSERT INTO MarketPrices (SecurityCode, BuyPrice, SellPrice, IsMarketOpen)
SELECT @SecurityCode, @BuyPrice, @SellPrice, @IsMarketOpen
EXCEPT
SELECT SecurityCode, BuyPrice, SellPrice, j.bool as IsActive FROM MarketPrices
CROSS JOIN (SELECT 0 as bool UNION SELECT 1 as bool ) as j
O
DECLARE @MktId int
SET @MktId = (SELECT SecurityId FROM MarketPrices
where SecurityCode = @SecurityCode
and BuyPrice=@BuyPrice
and SellPrice = @SellPrice)
IF (@MktId is NULL)
BEGIN
INSERT INTO MarketPrices (SecurityCode, BuyPrice, SellPrice, IsMarketOpen)
VALUES
(@SecurityCode,@BuyPrice, @SellPrice, @IsMarketOpen)
END
Asumir que@whatever
Es un parámetro de entrada en el procedimiento almacenado.
Quiero poder insertar un nuevo registro para cada SecurityCode cuando el BuyPrice o el SellPrice o ambos sean diferentes de cualquier otra ocurrencia anterior. No me importa IsMarketOpen.
¿Hay algo flagrantemente estúpido en cualquiera de los enfoques anteriores? ¿Es uno más rápido que el otro?