0

I am a beginner in SQL.This may be a old post but I did not get any simplified solution for that.

My concern is how to use IN clause in dynamic SQL where the IN items are based on the parameters having multiple values.

I have a table named Employee.

enter image description here

I have written a dynamic SQL that will return the employee lists where Department = 'IT,System'

SQL:

Declare @Department varchar(50)
Declare @SQL nvarchar(MAX)
Declare @Parameters nvarchar(50)

Set @Department='IT,System'
SET @SQL = 'select * from Employee where Department IN(@PDepartment)'     
SET @Parameters=N'@PDepartment nvarchar(50)'

--PRINT @SQL    
EXEC sp_Executesql @SQL,@Parameters,@PDepartment=@Department

This script is not working for more than one departments and returning no result. The same query is returning result if @Department = 'IT'

Here I have mentioned a small part of the real scenario. In the actual case the table name, the column name that will include in IN operator are both dynamic and will be accepted as stored proc parameter.

Thanks for the help.

0

2 Answers 2

2

This query should error, since you are missing single quotes around the elements of the list.

It would also be much simpler to use a table variable as an argument rather than a CSV string.

As for dealing with the string parameter, you don't really need dynamic SQL for this. If you are running SQL Server 2016 or higher, you can use table-valued function string_split():

select e.*
from employee e
where exists (
    select 1 from string_split(@Department, ',') where value = e.department
)

In ealier versions, you can use like:

select e.*
from employee e
where ',' + @Department + ',' like '%,' + e.department + ',%'
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @GMB for the answer. Here I have mentioned a demo. This is actually needed somewhere where I can use only the dynamic SQL. There the table name, the column name that should include IN operator are dynamic
1

I'm not very enthusiastic about this and you'd have to beware of there being apostrophes in the department names, but a simple solution may be:

Declare @Department varchar(50)
Declare @SQL nvarchar(MAX)

Set @Department='IT,System'
SET @SQL = 'select * from Employee where Department IN (''' + replace(@Department, ',', ''', ''') + ''')'

PRINT @SQL

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.