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:<
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