Stored procedure to parse a string

前端 未结 4 1093
小蘑菇
小蘑菇 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条回答
  •  旧时难觅i
    2021-01-25 14:22

    I definitely recommend doing your string parsing on the program side as opposed to the data side. That being said, if you absolutely must you can try doing something similar to this:

    DECLARE @String [nvarchar](256) = 'Name=Praveen | City=Hyderabad | Mobile=48629387429 | Role=User |'
    
    DECLARE @name [nvarchar](256) = (SELECT SUBSTRING(@String, CHARINDEX('Name=', @String)+5, CHARINDEX('|', @String)))
    
    DECLARE @city [nvarchar](256) = (SELECT SUBSTRING(@String, CHARINDEX('City=', @String)+5, CHARINDEX('|', @String)))
    
    DECLARE @mobile [nvarchar](256) = (SELECT SUBSTRING(@String, CHARINDEX('Mobile=', @String)+7, CHARINDEX('|', @String)))
    
    DECLARE @role [nvarchar](256) = (SELECT SUBSTRING(@String, CHARINDEX('Role=', @String)+5, CHARINDEX('|', @String)))
    
    SELECT RTRIM(LTRIM(LEFT(@name, CHARINDEX('|', @name)-1))) AS Name,
            RTRIM(LTRIM(LEFT(@city, CHARINDEX('|', @city)-1))) AS City,
            RTRIM(LTRIM(LEFT(@mobile, CHARINDEX('|', @mobile)-1))) AS Mobile,
            RTRIM(LTRIM(LEFT(@role, CHARINDEX('|', @role)-1))) AS Role
    

    This returns:

     Name    | City      | Mobile      | Role
    ________________________________________________
     Praveen | Hyderabad | 48629387429 | User
    

    Note that the length being addedfrom the CHARINDEX in the initial queries are equal to the search string.

    "Name=" is equal to 5 characters so we add 5 to move the index past the = sign, "Mobile=" is equal to 7 so we add 7.

    Similarly in the end SELECT query we are subtracting 1 from each CHARINDEX to remove the | symbol.

    Sources:

    SUBSTRING

    CHARINDEX

    LEFT

    LTRIM

    RTRIM

提交回复
热议问题