How to use IF/ELSE statement to update or create new xml node entry in Sql

前端 未结 3 2053
名媛妹妹
名媛妹妹 2020-12-02 00:33

Example:


    
        Lopez, Michelle MD
        Spanish
        

        
3条回答
  •  伪装坚强ぢ
    2020-12-02 01:13

    i hope this will help you

    Declare @locUrl varchar(255);
    Set @locUrl = 'xyz.aspx?id=' + '444' + '';
    
    declare @xml xml;
    set @xml = '
        
            Lopez, Michelle MD
            Spanish
            
                49 west point
            
            908-783-0909
            
                CM
            
            
            
        
    ';
    
    declare @chk nvarchar(max);
    -- here implementing for Value6
    set @chk = (select 
    C.value('(Value6/a/text())[1]', 'nvarchar(max)') col
    from
    @xml.nodes('/root/StartOne') as X(C))
    -- make sure here 
    select @chk;
    
    
    if @chk is null
    begin
    -- INSERT
    SET @xml.modify('       
    insert Value6 
    into (/root/StartOne/Value6)[1]') 
    end
    
    else
    begin
    -- UPDATE
    Set @xml.modify('replace value of (/root/StartOne/Value6/a/@href)[1] with sql:variable("@locUrl")');
    end
    
    select @xml
    

    UPDATE: after your below comment this is the way to update dynamically

    Declare @locUrl nvarchar(255);
    Set @locUrl = 'xyz.aspx?id=' + '444' + '';
    
    declare @xml xml;
    set @xml = '
        
            Lopez, Michelle MD
            Spanish
            
                49 west point
            
            908-783-0909
            
                CM
            
            
            
        
    ';
    
    declare @a  xml;
    set @a = N''+@locUrl+'';
    
    SET @xml.modify
    ('insert sql:variable("@a")
    into (/root/StartOne/Value6)[1]');
    
    select @xml;
    

提交回复
热议问题