Using comma separated value CSV parameter strings in SQL IN clauses

Below function when called with a CSV list returns a temporary table which can be used in “IN” of WHERE clause


/****** Object:  User Defined Function [dbo].[CSVTable]    ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE FUNCTION [dbo].[CSVTable] (@InStr VARCHAR(MAX))
RETURNS @TempTab TABLE
   (id varchar(10) not null)
AS
BEGIN

	SET @InStr = REPLACE(@InStr + ',', ',,', ',')
	DECLARE @SP INT
	DECLARE @VALUE VARCHAR(1000)
	WHILE PATINDEX('%,%', @INSTR ) <> 0 
	BEGIN
   		SELECT  @SP = PATINDEX('%,%',@INSTR)
   		SELECT  @VALUE = LEFT(@INSTR , @SP - 1)
   		SELECT  @INSTR = STUFF(@INSTR, 1, @SP, '')
   		INSERT INTO @TempTab(id) VALUES (@VALUE)
	END
	RETURN
END
GO

Using the code


DECLARE @CSV VARCHAR(200)
SET @CSV = '1,3'
SELECT * FROM Table WHERE id IN (SELECT * FROM dbo.CSVTable(@CSV))

Leave a Reply

Your email address will not be published.