All pastes #490543 Raw Edit

Sabba

public text v1 · immutable
·published 2007-05-16 02:06 UTC
rendered paste body
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go

ALTER FUNCTION [dbo].[fn_ParseCommaDelimitedList]
(
   @CommaDelimitedList varchar(4000)
)
RETURNS @TableVar TABLE (ItemID int NOT NULL ) 
AS
BEGIN
	IF @CommaDelimitedList IS NULL OR RTRIM(@CommaDelimitedList) = ''
		RETURN

                DECLARE @IDListPosition int 
                DECLARE @IDList varchar(4000)
                DECLARE @ArrValue varchar(4000) 
                SET @IDList = COALESCE(@CommaDelimitedList, '') 
                IF @IDList <> '' 
                BEGIN 
                -- Add comma to end of list so user doesn't have to 
                -- SET @IDList = @IDList + ',' 
                -- Loop through the comma demlimted string list 
                WHILE PATINDEX('%,%' , @IDList ) <> 0 
					BEGIN 
                        SELECT @IDListPosition = PATINDEX('%,%' , @IDList) 
                        SELECT @ArrValue = LEFT(@IDList, @IDListPosition - 1) 
                        -- Insert parsed ID into TableVar for "where in select"
                        INSERT INTO @TableVar (ItemID) VALUES (CONVERT(int, @ArrValue)) 
                        -- Remove processed string 
                        SELECT @IDList = STUFF(@IDList, 1, @IDListPosition, '') 
					END 
                END 
RETURN 

END