views:

28

answers:

1

Here is the pseudo-code for my inline query in my code:

select columnOne
from myTable
where columnOne = '#variableOne#'
  if len(variableTwo) gt 0
      and columnTwo = '#variableTwo#'
  end

I would like to move this into a stored procedure but am having trouble building the query correctly. I assume it would be something like

select columnOne
from myTable
where columnOne = @variableOne
  CASE
    WHEN len(@variableTwo) <> 0 THEN and columnTwo = @variableTwo
  END

This is giving me a syntax error.

Could someone tell me what I've got wrong.

Also, I would like to keep it to only one query and not just have one if statement. Also, I do not want to build the sql in the stored procedure and run Exec() on it.

+3  A: 

Switch up your logic and you can get the result you want.

select columnOne
from myTable
where columnOne = @variableOne
and (len(@variableTwo) = 0 or columnTwo = @variableTwo)
roufamatic
That takes care of one of my issues. The other is in the order by clause. I want to say something likeorder by CASE WHEN @variableThree = 'somevalue' THEN columnThree, END columnFourAny help with that?
Jason
If the two columns are the same datatype you can do a case statement: `ORDER BY CASE WHEN @variableThree='somevalue' THEN columnThree ELSE columnFour END` . If they are not, you could do some kind of casting, but if you're casting ints to varchars then it won't sort properly ('1000' will sort lower than '999'). I'd go with an IF statement at this point. :-)
roufamatic