读取XML并使用存储过程插入SQL表如果记录已存在而不是不插入 - 仅通过存储过程

时间:2014-12-13 13:34:28

标签: sql

我的查询: - 在此查询中,它仅适用于如果再次解析整个XML,而不会插入重复记录,但是如果您更改XML中的3条记录中的1条记录,那么它将再次插入所有记录,这意味着再次重复表中的记录,可以任何人请帮助我如何避免这个问题,看起来我需要使用游标或循环遍历每个记录,请帮助我我该怎么办。

这是我的代码

ALTER PROCEDURE [dbo].[SP_XMLtoTABLEInsert] 
(
    @xmlData XML ,
    @retValue varchar(20) OUTPUT
)
AS

    --SET @retValue =NULL;

    DECLARE @PolicyNumber VARCHAR(20) 
    DECLARE @CheckNumber VARCHAR(20) 
    DECLARE @Amount INT 

    SELECT                                                          
        @PolicyNumber=ISNULL(nref.value('PolicyNumber[1]','VARCHAR(50)'),''),                                             
        @CheckNumber=ISNULL(nref.value('CheckNumber[1]','VARCHAR(50)'),''),                                                          
        @Amount=ISNULL(nref.value('Amount[1]','int'),'')                                                                     
    FROM 
        @xmlData.nodes('tma/ tma_body / branchoperator') as R(nref)

    BEGIN
        IF EXISTS (SELECT 1 from [Employee2] where PolicyNumber = @PolicyNumber and CheckNumber = @CheckNumber and Amount = @Amount)
            BEGIN
                SET @retValue='Record Already Exist';
            END

        ELSE IF NOT EXISTS (SELECT 1 from [Employee2] where PolicyNumber = @PolicyNumber and CheckNumber = @CheckNumber and Amount = @Amount)
            BEGIN
                INSERT INTO [Employee2](PolicyNumber,CheckNumber,Amount,Collectiondate,NavDate,VendorName)
                SELECT
                    (R.ref.value('PolicyNumber[1]', 'varchar(20)')) as 'PolicyNumber',
                    R.ref.value('CheckNumber [1]', 'varchar(20)') as ' CheckNumber ',
                    R.ref.value('Amount[1]', 'int') as ' Amount',
                    R.ref.value('Collectiondate [1]', 'date') as ' Collectiondate',
                    R.ref.value('NavDate [1]', 'date') as ' NavDate',
                    R.ref.value('VendorName [1]', 'varchar(100)') as ' VendorName'
                FROM 
                    @xmlData.nodes('tma/ tma_body / branchoperator') as R(ref)

                IF(@@ROWCOUNT > 0 )
                SET @retValue='SUCCESS';
            END
    END

输入XML-

0 个答案:

没有答案