Click here to Skip to main content
15,886,519 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hello everyone,

I have a question about a query in a stored procedure.
When the used parmeter @parm is null in my where clause the syntax should be
SQL
and columnname in (select idfield from otherTable)

if the @parm is filled with a value the syntax should be:
SQL
and columnname = @parm


How to handle this problem in the where clause?
Posted

SQL
Declare @Query varchar(1000)

Set @Query = 'Select ColumnName1, columnName2, ..... From TableName1 Where ColumnName1 = ''Test'' and '

IF isnull(@parm, '') = ''
	Set @Query = @Query + 'CoulmnName2 in (Select CoulmnName2 from TableName2)'
ELSE
	Set @Query = @Query + 'CoulmnName2 = ' + @parm 

Execute @Query
 
Share this answer
 
v4
Comments
Herman<T>.Instance 24-Oct-11 7:06am    
this is not solving in the where clause. is it possible to solve in the where clause?
Hi,

Try this if could help...

IF @parm  is NULL        
  BEGIN        
   and columnname in (select idfield from otherTable) 
   else
     and columnname = @parm
  END  


Regards,
Al Moje
 
Share this answer
 
Comments
Herman<T>.Instance 24-Oct-11 6:03am    
thanks for thinking but this is NOT working. It fails on the IF, because in the where you start the lines with where, or, AND
You can do something like the following:

and (isnull(@parm,0) = 0 OR columnname in (select idfield from otherTable))

This will work for both the conditions.
 
Share this answer
 
Comments
Herman<T>.Instance 24-Oct-11 6:08am    
does not work either. because of the OR any value will return all possible values. In case a value is set, like 1 then only the values with 1 should return
Om Prakash Pant 24-Oct-11 6:50am    
in that case you need to add this in where clause. something like:
and (isnull(@parm,0) = 0 OR columnname in (select idfield from otherTable where param_field = @parm))
Otherwise it will return all values.
SQL
IF isnull(@parm, '') = ''
	Select * from TableName Where CoulmnName in (Select CoulmnName from TableName)
ELSE
	Select * from TableName Where CoulmnName = @parm
 
Share this answer
 
v2
Comments
Herman<T>.Instance 24-Oct-11 7:05am    
badly maintainable when using named columns
Admitting: this was a headache for 3 people but it works...


SQL
AND (@parm is null OR @parm = CASE
     WHEN Isnull(@parm,0) = 0 THEN
          CASE when columnName in (select id from table) then columnName
              ELSE @parm END
     ELSE
         ColumnName END)
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900