Tuesday, 12 August 2014

SQL variable with comma separated value with IN clauses


Declare @CommaVal  varchar(max)
set @CommaVal   = ' test1, test2 ,test3, test4'

If you want compare comma separated values in sql statement as below

Select * From Orders where description in (@CommaVal   )

The above stored procedure retrurns zero records even if description matches with one of comma separated values.

There are two ways to solve this problem.
1) Split comma separated values and stored in temporary table and make In query on temporary table.

2) Second option to do this thing without creating temporary table and It is as below.

Select * From Orders where

(ISNULL(@CommaVal   , SPACE(0)) = SPACE(0) OR ',' + (@CommaVal + ',' LIKE '%,' + CONVERT(nvarchar, description) + ',%')

No comments:

Post a Comment