1

I'm having poor database performance while inserting a big number of values. Before inserting I have to check if the value already exists and get its Id if it does, like in this query:

DECLARE @p0 int
DECLARE @p1 VARCHAR(255)

SET @p0 = 1
SET @p1 = '123123123123'

IF NOT EXISTS(SELECT TOP (1) Id 
           FROM Orders 
           WHERE MyId = @p0 AND Number = @p1) 
BEGIN       
   INSERT Orders (MyId, Number) VALUES  (@p0, @p1) 
END 
SELECT TOP (1) Id FROM Orders WHERE MyId = @p0 AND Number = @p1

Is there a better way to perform the operation?

APC
  • 144,005
  • 19
  • 170
  • 281
Bastianon Massimo
  • 1,710
  • 1
  • 16
  • 23

1 Answers1

2

That should be fast with the right indexing on the table (per comments above) so address that first.

However, you are querying the table twice, when you might be able to hit it once. Pseudocode:

declare @id int 

select @id = id FROM Orders WHERE MyId = @p0 AND Number = @p1

if ( @id is null )
begin

insert into ....

set @id = scope_identity()

end

select @id ...
onupdatecascade
  • 3,336
  • 22
  • 35