Using Variable in IN clause seems not to work, use SPIT Function in MSSQL
Example of using variable and SPLIT function in MSSQL.
Using Variable will NOT WORK with IN CONDITION
-- Table has following entries:
select name from employee where employee_id in ('101','102');
NAME
-----
RAM
SHAM
--Create procedure by using the IN clause with Variable but it not work:
CREATE PROCEDURE dbo.test(@p_id varchar(50))
as begin
Declare @v_splitstring varchar(100);
set @v_splitstring = CONCAT('''',RTRIM(REPLACE(@p_id,',',''',''')).'''');
select name from employee where employee_id in (@v_splitstring);
end;
-- Execute the procedure
-- Pass multiple employee id as 101,102 in string as parameter
EXEC dbo.test '101,102';
Output:
Nothing return...
Create the procedure with STRING_SPLIT function will WORK
-- Create with split function work with IN Condition:
CREATE PROCEDURE dbo.test(@p_id varchar(50))
as begin
select name from employee where employee_id in (select value from string_split(@v_splitstring,'.'));
end;
-- Execute the procedure
-- Pass multiple employee id as 101,102 in string as parameter
EXEC dbo.test '101,102';
Output:
NAME
-----
RAM
SHAM