How to pass string parameter with `IN` operator in stored procedure SQL Server 2008
Solution 1:
Here's how I solved it: Working SQL Fiddle
First I have create a function which splits the string value i.e. '1,2,4,5'
Split function:
CREATE FUNCTION fn_Split(@text varchar(8000), @delimiter varchar(20) = ' ')
RETURNS @Strings TABLE
(
position int IDENTITY PRIMARY KEY,
value varchar(8000)
)
AS
BEGIN
DECLARE @index int
SET @index = -1
WHILE (LEN(@text) > 0)
BEGIN
SET @index = CHARINDEX(@delimiter , @text)
IF (@index = 0) AND (LEN(@text) > 0)
BEGIN
INSERT INTO @Strings VALUES (@text)
BREAK
END
IF (@index > 1)
BEGIN
INSERT INTO @Strings VALUES (LEFT(@text, @index - 1))
SET @text = RIGHT(@text, (LEN(@text) - @index))
END
ELSE
SET @text = RIGHT(@text, (LEN(@text) - @index))
END
RETURN
END
Later in my query I use that split function
declare @startdate1 varchar(100) ='20120201'
declare @enddate1 varchar(100)='20130601'
declare @dptId varchar(100)='3,4'
select * from dummy
where DateJoining >=@startdate1 and DateJoining < @enddate1
and departmentID IN (SELECT Value FROM fn_Split(@dptId, ','));
Solution 2:
Try using sp_executesql
as the answer. Not the most efficient but it works
ALTER PROCEDURE [dbo].[uspTestReportData_GetBySerial]
@SerialNumbers nvarchar(200)
AS
BEGIN
SET NOCOUNT ON;
declare @sql nvarchar(200)
set @sql = 'SELECT * from MyTable WHERE Serial_Number in (' + @SerialNumbers + ')'
execute sp_executesql @sql
END
Solution 3:
Simply, you can do the following SELECT
:
SELECT M.REG_NO, T.TYPE_ID
FROM MAIN AS M
INNER JOIN CLASSIFICATION AS C
ON M.REG_NO = C.REG_NO
INNER JOIN TYPE AS T
ON T.TYPE_ID = C.TYPE_ID
WHERE (','+@Types+',') LIKE '%,' +T.TYPE_ID+ ',%'