-- =============================================
-- Author: Peter Gumpal
-- Create date: October 23, 2018
-- Description: This function was developed to transform a key-value pair delimited string into a table.
--usage as follows:
-- Select * from dbo.KVParser('LP=pH FM=(begin)[odor](add)[odor](end) US=pgumpal')
-- this will return 3 records containing keys: LP, FM and US. Between "=" are values so if the string
-- used is a CSV, the comma character will not be omitted.
-- Key limitation: Fixed to two characters, update code as required.
-- Note: Code not optimal, suggestions/mods are always welcome. - Peter :)
-- =============================================
CREATE FUNCTION [dbo].[KVParser]
(
@pKVString varchar(500)
)
RETURNS @kvtemp table ([key] varchar(2), [val] varchar(300))
AS
Begin
Declare @str varchar(500)
set @str = @pKVString -- 'LP=pH FM=(begin)[odor](add)[odor](end) US=pgumpal'
Declare @curKey varchar(2)
Declare @curChar varchar(1)
Declare @concatStr varchar(300)
Declare @ctrI int
Set @ctrI = 0
While (len(@str) > @ctrI)
Begin
Set @curChar = SUBSTRING(@str,@ctrI,1)
If (@curChar = '=')
Begin
Set @curKey = SUBSTRING(@str, @ctrI - 2 ,2) --get the key
--begin, get value from its right side
Set @ctrI = @ctrI + 1
Set @curChar = SUBSTRING(@str,@ctrI,1)
Set @concatStr = ''
--loop into the value
While (@curChar <> '='AND len(@str) >= @ctrI)
Begin
Set @curChar = SUBSTRING(@str,@ctrI,1)
Set @concatStr = isnull(@concatStr,'') + ISNULL(@curChar,'')
Set @ctrI = @ctrI + 1
End
--end, get value from its right side
Insert into @kvtemp([key],[val])
Select @curKey, LEFT(@concatStr, IIF(RIGHT(@concatStr,1)= '=', len(@concatStr)-3,len(@concatStr)))
--above IIF was added to trim the closing key and = / line needs improvement.
Set @ctrI = @ctrI - 3 --decrement counter to 3 to back read the key for the closing =
End
Set @ctrI = @ctrI + 1
End
Return
End