我在插入多个表时为处理事务创建了 SP,但在下面出现异常
我的SP
ALTER PROCEDURE [dbo].[usp_Insert_BankData]
@xmlBankItems XML ,
@xmlAccDetails XML,
@xmlPosition XML
AS
BEGIN
SET NOCOUNT ON;
DECLARE @TranStarted bit
SET @TranStarted = 0
IF( @@TRANCOUNT = 0 )
BEGIN
BEGIN TRANSACTION
SET @TranStarted = 1
END
ELSE
SET @TranStarted = 0
INSERT INTO BankItem([BankItemId],[PortfolioId],[ItemIdentifier],[ItemDisplayName])
SELECT r.value('BankItemId[1]','uniqueidentifier'),r.value('PortfolioId[1]','uniqueidentifier'),
r.value('ItemIdentifier[1]','bigint'),r.value('ItemDisplayName[1]','varchar(150)')
FROM @xmlBankItems.nodes('bankItem') t(r)
INSERT INTO BankAccountDetails (BankAccountId,BankItemId, AccountName,AccountDescription)
SELECT ac.value('BankAccountId[1]','uniqueidentifier'),ac.value('BankItemId[1]','uniqueidentifier'),
ac.value('AccountName[1]','varchar(150)'),ac.value('AccountDescription[1]','varchar(50)')
FROM @xmlAccDetails.nodes('accDetail') t(ac)
INSERT INTO Positions(PositionId,BankItemId,AccountCode,Ticker)
SELECT p.value('PositionId[1]','uniqueidentifier'),p.value('BankItemId[1]','uniqueidentifier'),
p.value('AccountCode[1]','bigint'),p.value('Ticker[1]','varchar(50)')
FROM @xmlPosition.nodes('position') t(p)
IF( @@ERROR <> 0 )
GOTO Cleanup
IF( @TranStarted = 1 )
BEGIN
SET @TranStarted = 0
COMMIT TRANSACTION
END
Cleanup:
IF( @TranStarted = 1 )
BEGIN
SET @TranStarted = 0
ROLLBACK TRANSACTION
END
END
- - - - - - - - -例外 - - - - - - - -
Violation of PRIMARY KEY constraint 'PK_BankAccountItems'. Cannot insert duplicate key in object 'dbo.BankItem'. The duplicate key value is (4bb6e35b-900b-4d0c-890e-48944abfe976).
Violation of PRIMARY KEY constraint 'PK_BankData_1'. Cannot insert duplicate key in object 'dbo.BankAccountDetails'. The duplicate key value is (952d89d6-bd3b-4408-b00d-644ab15ee9c0).
Violation of PRIMARY KEY constraint 'PK_Positions'. Cannot insert duplicate key in object 'dbo.Positions'. The duplicate key value is (4d030b2e-fbf3-40b7-9ae4-ab0aeb2138f0).
The statement has been terminated.
The statement has been terminated.
The statement has been terminated.