I am running into a deadlock issue when my stored procedure is called in sql server 2008. an xml string is passed into the stored procedure by biztalk and can be called many times in quick succession. The problem I am running into is that if the procedure is called 5 times in quick succession, the first 4 calls are rolled back and the last call is committed to the database due to the deadlock. Below is the code for the procedure - it uses OPENXML to parse the xml string and insert into Table A. I then take the new unique identifier from Table A and insert multiple child records into Table B. Any guidance on how to resolve this issue would be much appreciated.
Error Message: System.Data.SqlClient.SqlException (0x80131904): Transaction (Process ID XX) was deadlocked on lock resources with another process and has been chosen as the deadlock victim. Rerun the transaction.
Table Details
TableA
- Id int identity(1,1) Primary Key,
- ColumnA varchar(15) not null,
- ColumnB varchar(20) not null,
- AddedDateTime datetime default(getdate())
TableB
- Id int identity(1,1) Primary Key,
- TableAId int not null, (FK)
- ColumnC varchar(30) not null
XML
<Transactions>
<Transaction>
<ColumnA>Column A Value</ColumnA>
<ColumnB>Column B Value</ColumnB>
<ChildItems>
<ChildItem>
<ColumnC>Column C Value</ColumnC>
</ChildItem>
<ChildItem>
<ColumnC>Another Column C Value</ColumnC>
</ChildItem>
<ChildItem>
<ColumnC>Yet Another Column C Value</ColumnC>
</ChildItem>
</ChildItems>
Stored Procedure
CREATE PROCEDURE [dbo].[proc_ProcessXml]
(
@ResponseXml varchar(max)
)
WITH EXECUTE AS CALLER
AS
BEGIN TRANSACTION
DECLARE @xmlHandle int
declare @tableAId int
EXEC sp_xml_preparedocument @xmlHandle OUTPUT, @ResponseXml,
INSERT INTO TableA
(
ColumnA,
ColumnB
)
SELECT columnA, columnB
FROM OPENXML(@xmlHandle, '/Transactions/Transaction', 1)
WITH(
columnA varchar(15) 'ColumnA',
columnB varchar(20) 'ColumnB'
)
select @tableAId = SCOPE_IDENTITY()
INSERT INTO TableB
(
TableAId,
ColumnC
)
SELECT @tableAId, columnC
FROM OPENXML(@xmlHandle, '/Transactions/Transaction/ChildItems/ChildItem', 1)
WITH(
columnC varchar(30) 'ColumnC',
)
EXEC sp_xml_removedocument @xmlHandle
IF @@ERROR <> 0
BEGIN
ROLLBACK
END
ELSE
BEGIN
COMMIT
END