sql server 2008 - SQL parameter in where clause that allows for all, specific, or multiple values -
in sql server 2008 need able pass in parameter allows values, specific values, or multiple values. below sql works fine when parameter "all". , works fine single value. multiple values "msg 4145, level 15, state 1, line 7 expression of non-boolean type specified in context condition expected, near ','." i've tried number of things not getting it.
--works fine declare @sql varchar(8000) ,@p_code varchar(100) ,@v_code varchar(100) set @p_code = ('''all''') set @v_code = @p_code select @sql = 'select distinct code from table where '+@v_code+' in ('+'''all'''+') or code in ('+@v_code+')' execute (@sql) --returns records --works fine declare @sql varchar(8000) ,@p_code varchar(100) ,@v_code varchar(100) set @p_code = ('''abcd''') set @v_code = @p_code select @sql = 'select distinct code from table where '+@v_code+' in ('+'''all'''+') or code in ('+@v_code+')' execute (@sql) --returns records abcd --returns error noted declare @sql varchar(8000) ,@p_code varchar(100) ,@v_code varchar(100) set @p_code = ('''abcd'',''efgh''') set @v_code = @p_code select @sql = 'select distinct code from table where '+@v_code+' in ('+'''all'''+') or code in ('+@v_code+')' execute (@sql)
the left side of in should expression, code made not, is:
select distinct code table 'abcd','efgh' in ('all') or code in ('abcd','efgh')
which can see first in has problem not second.
you need change code logic like:
declare @sql varchar(8000) ,@v_code varchar(100) select @sql = 'select distinct code table ' + case when @v_code null '' else ' code in ('+@v_code+')' end execute (@sql)
and believe there better way perform this. if collection big in may cause performance issue.
Comments
Post a Comment