Stored procedure to parse a string

前端 未结 4 1089
小蘑菇
小蘑菇 2021-01-25 13:41

I need to write a stored procedure for which the input is a string.

The input string contains variable names and their values separated by pipeline delimiter like this:<

4条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-25 14:18

    One possible solution is use XML

    DECLARE @text VARCHAR(1000) 
            ,@xml xml
    
    SELECT @text = 'City=Hyderabad | Mobile=48629387429 | Role=User | Name =Praveen'
    
    SELECT @text = REPLACE(@text,'|','"')
        ,@text = REPLACE(@text,'=','="')
        ,@text = ''
    
    SELECT @xml = CAST(@text AS XML)
    
    select 
        line.col.value('@Name[1]', 'varchar(100)') AS Name
        ,line.col.value('@City[1]', 'varchar(100)') AS City
        ,line.col.value('@Mobile[1]', 'varchar(100)') AS Mobile 
        ,line.col.value('@Role[1]', 'varchar(100)') AS Role 
    FROM @xml.nodes('/row') AS line(col)
    

提交回复
热议问题