Tuesday, June 19, 2012

How to Comma Separate characters/words in a String

If you have a string of characters/words separated by comma and you want to comma separate each character/word in the string then you can use the following function.
Most often you come across this situation when you are passing an argurment to a Stored Procedure and the agruement being passed is a string of lets say ID_NO seperated by comma. In the Stored procedure you want to evaluate against each ID_NO in the string then you can use this function to comma separate each ID_NO

CREATE FUNCTION [dbo].[fn_CommaSeparatedValues]
(
@String VARCHAR(500)
)
 

RETURNS @Seperated TABLE
 (
Id  INT IDENTITY(1, 1) NOT NULL,
Value
VARCHAR(200)
 )

AS

BEGIN


DECLARE @Value VARCHAR(200)
DECLARE @StartPos bigint
DECLARE @EndPos bigint
DECLARE @LengthOfString int
DECLARE @ReachedEnd Char(1)
DECLARE @IndefOfComma INT
SET @StartPos=1
SET @EndPos=0
SET @LengthOfString=LEN(@String)
SET @ReachedEnd='N'

WHILE @ReachedEnd<>'Y'
BEGIN
SET @EndPos=CHARINDEX(',',@String,@StartPos)

 IF @EndPos>0

BEGIN
SET @Value = SUBSTRING(@String, @StartPos,@EndPos-@StartPos)
SET @StartPos=@EndPos+1
END

ELSE

BEGIN
SEt @ReachedEnd='Y'
SET @Value = SUBSTRING(@String, @StartPos,@LengthOfString-(@StartPos-1))
END

INSERT INTO @Seperated(Value) VALUES(@Value)

END
RETURN
END

0 comments:

Post a Comment