• If you want to avoid dynamic SQL, you could use an UDF that will convert comma-delimited string to a table-type variable, and then use IN as usual.

    SELECT * FROM customers

    WHERE ISNULL(@cust_id_multiple, '') = '' OR customers.cust_id IN (SELECT value FROM dbo.LIST_TO_TABLE(@cust_id_multiple))

     

    Below is a sample UDF that does the trick.

    --converts list of values to a temporary table. Used to avoid dynamic SQL statements when IN clause is used as filter expression

    --sList: list of numeric values in comma-separated form, to be converted to table

    --return value: table-type variable containing one column. The table is filled with numeric values from @sList

    CREATE FUNCTION LIST_TO_TABLE (@sList AS VARCHAR(255))

    RETURNS  @retTable TABLE(value VARCHAR(50))  AS 

    BEGIN

     IF @sList IS NULL RETURN

     --preparing the input list, removing IN keyword and parenthesis

     SET @sList = REPLACE(@sList, 'IN(','')

     SET @sList = REPLACE(@sList, 'IN (','')

     SET @sList = REPLACE(@sList, '(','')

     SET @sList = REPLACE(@sList, ')','')

     SET @sList = LTRIM(RTRIM(@sList))

     --scrolling thru values in @sList and populating temporary table

     DECLARE @index INT, @Delimiter CHAR(1)

     DECLARE @Result VARCHAR(255)

     SET @Delimiter = ','

     WHILE @sList <> ''

     BEGIN

      SET @index = CHARINDEX(@Delimiter, @sList)

      IF @index <> 0

      BEGIN

       SET @Result = LEFT(@sList, @index - 1)

       SET @sList = SUBSTRING(@sList, @index + 1, LEN(@sList))

      END

      ELSE

      BEGIN

       SET @Result = @sList

       SET @sList = ''

      END

      INSERT @retTable SELECT @Result

     END

     RETURN

    END