使用FK关系在单个事务中插入多个表

时间:2013-01-31 04:55:07

标签: asp.net sql

我在插入多个表但在

下面获得异常时为句柄事务创建了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.

1 个答案:

答案 0 :(得分:0)

听起来问题是错误中提到的表中已存在重复数据。该错误提供了违反的键值。查询表中的那些键 - 如果它们存在,插入将失败,并且事务将无法帮助您。