Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 3236034
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 17, 20262026-05-17T17:34:31+00:00 2026-05-17T17:34:31+00:00

I have an insert statement that was deadlocking using linq. So I placed it

  • 0

I have an insert statement that was deadlocking using linq. So I placed it in a stored proc incase the surrounding statements were affecting it.

Now the Stored Proc is dead locked. Something about the insert statement is locking itself according to the Server Profiler. It claims that two of those insert statements were waiting for the PK index to be freed:

When I placed the code in the stored procedure it is now stating that this stored proc has deadlocked with another instance of this stored proc.

Here is the code. The select statement is similar to that used by linq when it did its own query. I simply want to see if the item exists and if not then insert it. I can find the system by either the PK or by some lookup values.

       SET NOCOUNT ON;
       BEGIN TRY
        SET TRANSACTION ISOLATION LEVEL SERIALIZABLE

        BEGIN TRANSACTION SPFindContractMachine
        DECLARE @id int;
        set @id = (select [m].pkID from Machines as [m]
                        WHERE ([m].[fkContract] = @fkContract) AND ((
                        (CASE 
                            WHEN @bByID = 1 THEN 
                                (CASE 
                                    WHEN [m].[pkID] = @nMachineID THEN 1
                                    WHEN NOT ([m].[pkID] = @nMachineID) THEN 0
                                    ELSE NULL
                                 END)
                            ELSE 
                                (CASE 
                                    WHEN ([m].[iA_Metric] = @lA) AND ([m].[iB_Metric] = @lB) AND ([m].[iC_Metric] = @lC) THEN 1
                                    WHEN NOT (([m].[iA_Metric] = @lA) AND ([m].[iB_Metric] = @lB) AND ([m].[iC_Metric] = @lC)) THEN 0
                                    ELSE NULL
                                 END)
                         END)) = 1));
        if (@id IS NULL)
        begin
            Insert into Machines(fkContract, iA_Metric, iB_Metric, iC_Metric, dteFirstAdded) 
                values (@fkContract, @lA, @lB, @lC, GETDATE());

            set @id = SCOPE_IDENTITY();
        end

        COMMIT TRANSACTION SPFindContractMachine

        return @id;

    END TRY
    BEGIN CATCH
        if @@TRANCOUNT > 0
            ROLLBACK TRANSACTION SPFindContractMachine
    END CATCH
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-17T17:34:31+00:00Added an answer on May 17, 2026 at 5:34 pm

    Any procedure that follows the pattern:

    BEGIN TRAN
    check if row exists with SELECT
    if row doesn't exist INSERT
    COMMIT
    

    is going to run into trouble in production because there is nothing to prevent two treads doing the check simultaneously and both reach the conclusion that they should insert. In particular, under serialization isolation level (as in your case), this pattern is guaranteed to deadlock.

    A much better pattern is to use database unique constraints and always INSERT, capture duplicate key violation errors. This is also significantly more performant.

    Another alternative is to use the MERGE statement:

    create procedure usp_getOrCreateByMachineID
        @nMachineId int output,
        @fkContract int,
        @lA int,
        @lB int,
        @lC int,
        @id int output
    as
    begin
        declare @idTable table (id int not null);
        merge Machines as target
            using (values (@nMachineID, @fkContract, @lA, @lB, @lC, GETDATE()))
                as source (MachineID, ContractID, lA, lB, lC, dteFirstAdded)
        on (source.MachineID = target.MachineID)
        when matched then
            update set @id = target.MachineID
        when not matched then
            insert (ContractID, iA_Metric, iB_Metric, iC_Metric, dteFirstAdded)
            values (source.contractID, source.lA, source.lB, source.lC, source.dteFirstAdded)
        output inserted.MachineID into @idTable;
        select @id = id from @idTable;
    end 
    go
    
    create procedure usp_getOrCreateByMetrics
        @nMachineId int output,
        @fkContract int,
        @lA int,
        @lB int,
        @lC int,
        @id int output
    as
    begin
        declare @idTable table (id int not null);
        merge Machines as target
            using (values (@nMachineID, @fkContract, @lA, @lB, @lC, GETDATE()))
                as source (MachineID, ContractID, lA, lB, lC, dteFirstAdded)
        on (target.iA_Metric = source.lA
            and target.iB_Metric = source.lB
            and target.iC_Metric = source.lC)
        when matched then
            update set @id = target.MachineID
        when not matched then
            insert (ContractID, iA_Metric, iB_Metric, iC_Metric, dteFirstAdded)
            values (source.contractID, source.lA, source.lB, source.lC, source.dteFirstAdded)
        output inserted.MachineID into @idTable;
        select @id = id from @idTable;
    end 
    go
    

    This example separates the two cases, since T-SQL queries should never attempt to resolve two different solutions in one single query (the result is never optimizable). Since the two tasks at hand (get by mahcine id and get by metrics) are completely separate, the should be separate procedures and the caller should call the apropiate one, rather than passing a flag. This example shouws how to achieve the (probably) desired result using MERGE, but of course, a correct and optimal solution depends on the actual schema (table definition, indexes and cosntraints in place) and on the actual requirements (is not clear what the procedure is expected to do if the criteria is already matched, not output and @id?).

    By eliminating the SERIALIZABLE isolation, this is no longer guaranteed to deadlock, but it may still deadlock. Solving the deadlock is, of course, completely dependent on the schema which was not specified, so a solution to the deadlock cannotactually be provided in this context. There is a sledge hammer of locking all candidate row (force UPDLOCK or even TABLOCX) but such a solution would kill throughput on heavy use, so I cannot recommend it w/o knowing the use case.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a SQL script that inserts data (via INSERT statements currently numbering in
I have a SQL Insert query inside a stored proc, for inserting rows into
I have an insert statement that pulls some data into a few table variables
I have an INSERT INTO ... ON DUPLICATE KEY UPDATE ... statement that executes
I have a stored procedure in SQL Server 2008 that will insert a record
I have two insert statements, almost exactly the same, which run in two different
Using POSIX threads & C++, I have an Insert operation which can only be
I have a long running insert transaction that inserts data into several related tables.
I had a parametrized insert statement that was working well and I needed to
I have a stored procedure that works correctly when I execute the stored procedure

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.