0

我想获得有关改进导致 sql 服务器返回死锁消息的设置的建议。我有多个线程应用程序,它实际上使用 TaskParallel 库,每个任务将使用一个存储过程从表中选择一个 id 以用于其处理。我立即在同一语句中从表中删除了该 ID,我认为这就是导致死锁的原因。该表由一列没有索引的唯一 ID 组成。我曾想过定期进行批量删除,但这意味着要在多个服务器上保留已用 id 的计数。

这是我的 sql 存储过程:

   CREATE PROCEDURE [dbo].[get_Ids]
   @id nvarchar(20) OUTPUT

    AS

    BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
   SET NOCOUNT ON;

       Select top 1 @id = siteid from siteids 
       delete siteids where siteid = @id



   END

有没有更好的方法来做到这一点?我的流程工作得非常快,我曾经从 webrequest 服务请求这个 id,但这需要 3 秒。

4

1 回答 1

1

Some things to try: Maybe try hinting to the DB that you will delete the record you just selected, this way it will grab the lock early. For this to work you'll need to wrap the whole procedure in a transaction, then hint the select. Should look something like:

BEGIN TRANSACTION  
  SELECT TOP 1 @id = siteid from siteids WITH (UPDLOCK, HOLDLOCK)
  DELETE siteids WHERE siteid = @id
COMMIT TRANSACTION

Also make sure the siteid column is indexed(or tag it as primary key, since you say it is unique), otherwise it would have to scan the table to get the record to delete, which could make deadlocking worse since it spends a bunch more time deleting.

For deadlocks in general, run the SQL profiler and see what the deadlock graph looks like - might be something else is going on.

于 2012-11-03T04:46:21.663 回答