@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.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Muhammad Imran AnsariRank #326 · 7.6K reputationPosted Jan 22, 2025, 1:01 AM EST
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:
DECLARE @Status1 NVARCHAR(MAX) SET @Status1 = 'AB,AD' SELECT * FROM EMPLOYEE WHERE STATUS IN (SELECT value FROM STRING_SPLIT(@Status1, ','))Using Dynamic SQL query:
DECLARE @Status1 NVARCHAR(MAX) SET @Status1 = '''AB'', ''AD''' -- Manually wrap the values with single quotes for dynamic SQL DECLARE @SQL NVARCHAR(MAX) SET @SQL = N'SELECT * FROM EMPLOYEE WHERE STATUS IN (' + @Status1 + ')'Happy Coding. Thank you!
Tuhin PaulRank #7 · 71.9K reputationPosted Jan 22, 2025, 1:12 AM EST
You need to split the values in the string into individual rows that SQL Server can use in the
INclause.DECLARE @Status1 TABLE (StatusValue NVARCHAR(MAX)); -- Insert values into the table INSERT INTO @Status1 (StatusValue) VALUES ('AB'), ('AD'); -- Query using IN SELECT * FROM EMPLOYEE WHERE STATUS IN (SELECT StatusValue FROM @Status1);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.Tuhin PaulRank #7 · 71.9K reputationPosted Jan 22, 2025, 1:17 AM EST
If you're working with a comma-separated string, you can use a string-splitting function like
STRING_SPLIT(available in SQL Server 2016+).DECLARE @Status1 NVARCHAR(MAX); SET @Status1 = 'AB,AD'; -- Query using STRING_SPLIT SELECT * FROM EMPLOYEE WHERE STATUS IN (SELECT value FROM STRING_SPLIT(@Status1, ','));see below the execution flow for this query.