Groups | Blog | Home
all groups > sql server clients > december 2004 >

sql server clients : Problem Using if condition in select stored procesure



Scott Morris
12/21/2004 8:54:21 AM
This is not a recommended usage since the optimizer will probably not
generate a good plan. It would be better to use a IF statement and two
select statements. In addition, I find the logic more than a bit strange.
In any event, below is an example

use Northwind
go
--select * from invoices

declare @a int

/*set @a = 14
select * from invoices
where ProductID = @a

set @a = 10249
select * from invoices
where OrderID = @a*/

set @a = 10249
set @a = 14
select * from invoices
where case when @a > 1000 then OrderID else @a end = @a
and case when @a <= 1000 then ProductID else @a end = @a




[quoted text, click to view]

microsoft
12/21/2004 3:07:13 PM
Hi!
how can i use if condition in where clause of select statement
I want the work like this
but this is not working correct
select * from Table1
where
if (@a>1)
field1=@a
else
field2=@a

Milton Li
12/23/2004 2:41:01 PM
select * from Table1 where @a>1 and field1=@a
Union
select * from Table1 where @a<1 and field2=@a


[quoted text, click to view]
Steve Kass
12/31/2004 1:14:28 AM


where
(@a > 1 and field1 = @a) or (@a <= 1 and field2 = @a)

or (probably less efficient)

where
@a = case when @a > 1 then field1 else field2 end

If you have a non-ansi setting for null comparisons,

where
(@a > 1 and field1 = @a) or ((@a <= 1 or @a is null) and field2 = @a)

Steve Kass
Drew University

[quoted text, click to view]
AddThis Social Bookmark Button