문제

My case scenario passes parameter to a procedure, that only does an insert. But two threads might try to pass the same value.

How to handle this situation w/out throwing an exception and with least amount of locks?

My performance requirement is at least 10k inserts per second.

EDIT: Column is unique. Timestamp might be altered (adjusted) before insertion.

도움이 되었습니까?

해결책

Create index on table with ignore duplicate key option. It will not insert duplicate row and also won't through any error.

E.g.

create unique index i1 on #tmp(id) with ignore_dup_key

insert into #tmp values(1,"A")
2> go
(1 row affected)


1> insert into #tmp values(1,"A")
2> go
Duplicate key was ignored.
(0 rows affected)

다른 팁

Try the MERGE statement

From MSDN . A common scenario is updating one or more columns in a table if a matching row exists, or inserting the data as a new row if a matching row does not exist. This is usually done by passing parameters to a stored procedure that contains the appropriate UPDATE and INSERT statements. With the MERGE statement, you can perform both tasks in a single statement.

Regarding your performance concerns, there is also a page on Optimizing MERGE Statement Performance

As @Martin Smith has pointed out there is good solution - even though it is contrary to my question, it has good reasoning behind that seems well supported. The original answer you can find here posted by @gbn.

BEGIN TRY
   INSERT etc
END TRY
BEGIN CATCH
    IF ERROR_NUMBER() <> 2627
      RAISERROR etc
END CATCH

Seriously, this is quickest and the most concurrent without locks, especially at high volumes. What if the UPDLOCK is escalated and the whole table is locked?

The original text by Paul Nielsen you can find here. - lesson 4.

If anyone has a similar problem to mine it is good to have a look at it.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top