First create a Split function which will take a comma separated string as input and return a table:
CREATE FUNCTION [dbo].Split(@input AS Varchar(4000) )
RETURNS
@Result TABLE(Value BIGINT)
AS
BEGIN
DECLARE @str VARCHAR(20)
DECLARE @ind Int
IF(@input is not null)
BEGIN
SET @ind = CharIndex(',',@input)
WHILE @ind > 0
BEGIN
SET @str = SUBSTRING(@input,1,@ind-1)
SET @input = SUBSTRING(@input,@ind+1,LEN(@input)-@ind)
INSERT INTO @Result values (@str)
SET @ind = CharIndex(',',@input)
END
SET @str = @input
INSERT INTO @Result values (@str)
END
RETURN
END
Second, do this to get result:
DECLARE @allNeededIds as varchar(max)
set @allNeededIds = '1,2,3,4,5,6'
select value into temp from Split(@allNeededIds)
Final query would be:
SELECT * FROM table1
WHERE id IN (select value in temp)