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