Technical Article

UDF: Parse a delimited list of paramters

,

After replying to a post today I thought I'd share this with all.

This is a user defined function that I use to return a table of parameters passed in a parameter string.

Function Usage
Select * From dbo.fnParseParamString ([@ParamString='Delimited String of parmaters'],[@Delimeter='Delimiting Character'])

Lets say you are concatenating a list of form data from a web page where you take the user's First Name, Last Name and email address.

your concatenated string looks like this: John,Doe,jdoe@company.com

Once you've installed the userdefined function you can execute this:

select * from dbo.fnParseParamString('John,Doe,jdoe@company.com',',')

this returns

iRowId vcParameters
----------- --------------------
1 John
2 Doe
3 jdoe@company.com

(3 row(s) affected)

now, since you know Parameter 1 is the first name, and parameter 2 is the last name and parameter 3 is the email address you can do something like this:

select vcParameter from dbo.fnParseParamString('John,Doe,jdoe@company.com',',') where iRowId = 3

which returns the email address portion of the parameter string

vcParameters
--------------------
jdoe@company.com

(1 row(s) affected)

IF EXISTS(Select * from sysobjects where id = OBJECT_ID(N'fnParseParamString'))
 DROP FUNCTION fnParseParamString

GO

CREATE FUNCTION dbo.fnParseParamString (@ParamString VARCHAR(8000),@Delimeter VARCHAR(1))

 RETURNS @tblParams TABLE(iRowId INT IDENTITY(1,1),vcParameters VARCHAR(255))

 AS

 BEGIN
  -- PARSE PARAMETER STRING
  DECLARE @vcParameter VARCHAR(255)
 
  DECLARE @iStart INT
  DECLARE @iEnd INT
  DECLARE @iLength INT
  
  SET @iStart = 0
  SET @iEnd = len(@ParamString)
 
  WHILE @iEnd <> 0
  BEGIN
   SET @iEnd = CHARINDEX(@Delimeter,@ParamString,@iStart)
   SET @iLength = @iEnd - @iStart
   IF @iLength < 0
    SET @iLength = len(@ParamString)
 
   SET @vcParameter = SUBSTRING(@ParamString,@iStart,@iLength)
 
   INSERT INTO @tblParams Select @vcParameter
 
   SET @iStart = @iEnd+1
  END
 
  RETURN
 END

GO

-- EXECUTE THE FUNCTION TO RETURN A LIST OF PARAMETERS THIS CAN BE USED WHEN THE PARAMETERS IN THE LIST ARE ALWAYS IN THE SAME ORDER
-- EXAMPLE
select * from dbo.fnParseParamString('John|Doe|jdoe@company.com','|')
select vcParameters from dbo.fnParseParamString('John,Doe,jdoe@company.com',',') where iRowId = 3

Rate

You rated this post out of 5. Change rating

Share

Share

Rate

You rated this post out of 5. Change rating