Technical Article

t-sql function to parse string data

,

The below function can be used to parse or split out data from a delimited string. The function takes in 3 parameters. The text you want to parse, the 1 character delimiter, and the total count of objects in the text.

Text for function is set at size of varchar(2000), feel free to make bigger if you wish. Also, delimiter is set to be 1 character, you may use any character you wish.

When calling function make sure to pass objects in that order as in below example. The function will then return a table datatype of size varchar(300) breaking out all objects in text. Again you may make this bigger as well.

Lastly, make sure when passing in text to function you end your text with delimiter.

Example of call to function, call assumes function resides in master database. delimiter is a comma, total records = 6.

SELECT * FROM [master].[dbo].[parsestring]('abcd,efg,hij,klm,no,pq,',',',6)


SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO


/******************************************************************************
*File Name:dbo.parsestring 
*File Desc:Will split out array data.
*Database:MASTER
*Language:MS Transact-SQL 
*Version:MS SQL 2000
*
*Tables:N/A
*
*
*  
*Procedures:N/A
*
*Date:1/13/2005
*Author:KILEY MILAKOVIC
*Architect:
*
*Special Comments/Warnings
*None
*
*******************************************************************************
*Function Name:dbo.parsestring 
*
*Function Desc:Split out array data.
*
*Parameters:
* @txtarray varchar(2000)= Text to be parsed
*     @delimit  char(1) = delimiter used to delimIt array data 
*        @reccount int    = number of objects in array
*
*RETURNS: @tabsplit table variable of all parsed values
*
*Notes:
*None
********************************************************************************/
create  FUNCTION dbo.parsestring (@txtarray varchar(2000), @delimit char(1),@reccount int)  
RETURNS @tabsplit table(txtout varchar(300))
AS   
BEGIN 
declare @loopcount int,
@holdpos int,
@holdpos2 int

set @loopcount = 1
set @holdpos2 = 1
set @holdpos = 1
while @loopcount <= @reccount
begin

        select @holdpos = charindex(@delimit,@txtarray,@holdpos + 1)
insert  @tabsplit
                select SUBSTRING (@txtarray, @holdpos2, @holdpos - @holdpos2) 
        set @holdpos2 = @holdpos + 1
        Set @loopcount = @loopcount + 1
end 
RETURN 
END




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

Rate

You rated this post out of 5. Change rating

Share

Share

Rate

You rated this post out of 5. Change rating