Search code examples
sqlsql-server-2008in-clause

SQL Server - In clause with a declared variable


Let say I got the following :

DECLARE @ExcludedList VARCHAR(MAX)

SET @ExcludedList = 3 + ', ' + 4 + ' ,' + '22'

SELECT * FROM A WHERE Id NOT IN (@ExcludedList)

Error : Conversion failed when converting the varchar value ', ' to data type int.

I understand why the error is there but I don't know how to solve it...


Solution

  • You need to execute this as a dynamic sp like

    DECLARE @ExcludedList VARCHAR(MAX)
    
    SET @ExcludedList = '3,4,22,6014'
    declare @sql nvarchar(Max)
    
    Set @sql='SELECT * FROM [A] WHERE Id NOT IN ('+@ExcludedList+')'
    
    exec sp_executesql @sql