Sending a list of parameters for an IN in SQL

posted in: Uncategorized | 0

BronwenWeeGo.jpgI needed to write a sql statement in SQL2000 that took a string containing all the values i wanted to match IN a parameter, but the parameter is an integer.

Essentially, I wanted to write

SELECT * FROM Foo where Foo.ID IN ( @parmlist )

So i ended up with a function that splits the string on a supplied delimiter into a table as follows

CREATE FUNCTION [dbo].[fnSplit](
 @SplitString varchar(8000)
,@Delimiter   varchar(10)
)
RETURNS @SplitTable TABLE (val varchar(100))
AS

 BEGIN
  DECLARE @FC int SET @FC = -1
  WHILE (Len(@SplitString) > 0)
  BEGIN 
   SET @FC = CHARINDEX(@Delimiter , @SplitString) 
   IF (@FC = 0) AND (LEN(@SplitString) > 0) 
   BEGIN  
    INSERT INTO @SplitTable
    VALUES (@SplitString)  
    BREAK 
   END 
   IF (@FC > 1) 
   BEGIN  
    INSERT INTO @SplitTable
    VALUES (LEFT(@SplitString, @FC - 1))  
    SET @SplitString = RIGHT(@SplitString, (LEN(@SplitString) - @FC)) 
   END 
   ELSE
    SET @SplitString = RIGHT(@SplitString, (LEN(@SplitString) - @FC))
  END
RETURN
END

Then joined it in my IN as follows: 

SELECT * from Foo where Foo.ID IN (select val from dbo.fnSplit(@paramList, ','  ))

Hmm..not nice..is there a better way to do this?