Using IN clause with SPLIT function in MSSQL

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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.