@Status1 nvarchar(max)
SET @Status1 IN ('AB','AD')
SELECT * FROM EMPLOYEE WHERE STATUS IN (@Status1 )
@Status1 nvarchar(max)
SET @Status1 IN ('AB','AD')
SELECT * FROM EMPLOYEE WHERE STATUS IN (@Status1 )
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Muhammad Imran AnsariPosted Jan 22, 2025, 6:01 AM
Hello,
SQL Server doesn't interpret the contents of a single string variable as a list when used in an IN clause. Instead, you need to split the string into individual values. You can use either STRING_SPLIT function (SQL Server 2016 or later) or Dynamic SQL query to achieve this.
Using STRING_SPLIT:
Using Dynamic SQL query:
Happy Coding. Thank you!
Tuhin PaulPosted Jan 22, 2025, 6:17 AM
If you're working with a comma-separated string, you can use a string-splitting function like
STRING_SPLIT(available in SQL Server 2016+).see below the execution flow for this query.
Tuhin PaulPosted Jan 22, 2025, 6:12 AM
You need to split the values in the string into individual rows that SQL Server can use in the
INclause.You can declare a table variable to hold the statuses.
Execution Plan Breakdown
Insert Into
@Status1Table Variable:Subquery Evaluation (
SELECT StatusValue FROM @Status1):@Status1table variable to extract the values for theINclause.Main Query Execution (
SELECT * FROM EMPLOYEE WHERE STATUS IN (...)):EMPLOYEEtable based on theSTATUScolumn.STATUSis indexed, SQL Server uses an Index Seek to quickly locate rows matching the values from the subquery.STATUSis not indexed, SQL Server scans the entireEMPLOYEEtable to evaluate the condition.Row Matching:
INclause by comparingSTATUSvalues against the results of the subquery.